#include "yb_form_dzbl.h"
#include "pub_var.h"
#include "ui_yb_form_dzbl.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
#include <QSqlError>
#include <QSqlRecord>
#include <QDateTime>
#include <QMap>
#include <QDir>

Form_dzbl::Form_dzbl(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_dzbl)
{
    ui->setupUi(this);

    //暂时不需要医保结算单

    ui->rbJjjs->setEnabled(false);

    //设置字体
    ui->tvList->setFont(this->font());

    // 读取配置文件
    QSettings setIni("clin.ini", QSettings::IniFormat);

    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/dzbl").toRect();
    this->setGeometry(rct);
    ui->pbAll->setVisible(false);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qrmt = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);

    //默认日期
    QDate dt;
    ui->deStart->setDate(dt.currentDate());
    ui->deEnd->setDate(dt.currentDate());

    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    isAll = false;  //批量传输
    //ui->pbTemp->setVisible(false);
    ui->cbYb->setVisible(false);

    //保留最近5次日志文件
    QString basePath = pub::base_path + "/logs/upload";
    QDir d = QDir(basePath);
    d.setNameFilters( QStringList("*.log") );
    d.setSorting(QDir::Name);   //sorted by name, reversed.
    d.setSorting(QDir::Reversed);
    QStringList files = d.entryList();  //read filenames

    for(int i = 5; i < files.size() ; i++){
        QFile f(basePath + "/" + files[i]);
        f.remove();
    }

    QString fileName = "logs/upload/" + QDate::currentDate().toString("yyyyMMdd") + ".log";

    logFile =  new QFile(fileName);

    //检索系统当前用户查询权限
    sq = "select role_dept from com_privileges where code = '" + pub::usr_code + "' and role_dept = '医保'";
    qDebug()<<"检索系统当前用户查询权限 : "<<sq;
    qrm->exec(sq);
    if(qrm->size() < 1)
    {
        isInsuManager = false;
        ui->groupBox_2->setVisible(false);

        //ui->deEnd->setVisible(false);
    }
    else
    {
        isInsuManager = true;
        ui->groupBox_2->setVisible(true);

        //ui->deEnd->setVisible(true);
    }

    ui->pbTemp->setVisible(false);
    ui->groupBox_2->setEnabled(false);
}

Form_dzbl::~Form_dzbl()
{
    delete ui;
}

void Form_dzbl::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/dzbl", QVariant(this->geometry()));
    if(logFile->isOpen())
    {
        logFile->flush();
        logFile->close();
    }

    destroyW("dzbl");

}

void Form_dzbl::on_pbSearch_clicked()
{
    if(!ui->cbUnUpload->isChecked() && !ui->cbUploaded->isChecked())
    {
        QMessageBox::information(this,"注意","已上传和未上传至少要选择一项！");
        return;
    }

    if(!ui->ckb_dt->isChecked() && !ui->cbSingle->isChecked())
    {

        QMessageBox::information(this,"注意","日期和限定至少要选择一项！");
        return;
    }

    ui->ptText->clear();

    sq = "select to_char(oper_date, 'yyyy-mm-dd') 挂号日期, "
         " to_char(receipt_doct_date, 'yyyy-mm-dd') 处置日期, "
         "card_no 病志号, name 姓名, dept_name 诊室, "//0 - 4
         "clinic_code, 'doct_name', pact_name, "
         "to_char(oper_date, 'yyyy-mm-dd hh24:mi:ss'), dept_code , rowid, "//5 - 10
         "(case when sex_code = 'F' then '女' else '男' end) gend, "
         "to_number(reg_date - birthday)/365, mcard_no,"//11 - 13
         "doct_code, doct_name, see_docd, invoice_no, ynfr,idenno" //14 - 19
         " from fin_opr_register "
         " where valid_flag = '1' ";

    if(!isInsuManager)
    {
        //无医保管理权限，对数据进行限制，查询只返回本人数据
        sq += " and  (see_docd='" + pub::usr_code + "' or (doct_code='"+pub::usr_code+"' and see_docd is null )) ";
        sq += " and dept_code = '" + pub::dp_code + "'";
        //sq += " and trunc(oper_date) = to_date('" + ui->deStart->date().toString("yyyy-MM-dd") + "','yyyy/mm/dd')";
    }

    //未接诊记录，receipt_doct_date 字段无信息，只能用 oper_date 提取。
    //receipt_doct_date 记录最后处方时间，oper_date 与 reg_date相同。
    if(ui->ckb_dt->isChecked())
    {
        sq += " and ((receipt_doct_date > to_date('"
                + ui->deStart->date().toString("yyyy-MM-dd")
                + "','yyyy/mm/dd')";
        sq += " and receipt_doct_date < to_date('"
                + ui->deEnd->date().toString("yyyy-MM-dd")
                +" 23:59:59','yyyy/mm/dd hh24:mi:ss'))  ";
        sq += " or (oper_date > to_date('"
                + ui->deStart->date().toString("yyyy-MM-dd")
                + "','yyyy/mm/dd')";
        sq += " and oper_date < to_date('"
                + ui->deEnd->date().toString("yyyy-MM-dd")
                +" 23:59:59','yyyy/mm/dd hh24:mi:ss')))  ";
    }


    //指定限制条件
    if(ui->cbSingle->isChecked()){


        if(ui->leBzh->text().trimmed().isEmpty()){
            QMessageBox::warning(this, "注意","未指定有效的限定信息！" );
            return;
        }

        QString cond = ui->leBzh->text().trimmed();
        QString tmp_sq;

        if(ui->cbb_cond->currentText() == "病志号")
        {
            sq += " and card_no = '" + pub::add0(cond,10) + "' ";
        }
        else if(ui->cbb_cond->currentText() == "就诊ID")
        {
            tmp_sq = "select inpatient_no "
                     " from fin_ipr_siinmaininfo where mdtrt_id ='"
                     + cond + "'";
            qro->exec(tmp_sq);
            qro->next();
            sq += " and clinic_code = '" + qro->value(0).toString() + "' ";
            qDebug()<<"通过就诊ID查找clinic code"<<"\n";
        }
        else if(ui->cbb_cond->currentText() == "人员编号")
        {
            tmp_sq = "select inpatient_no "
                    " from fin_ipr_siinmaininfo where psn_no ='"
                    + cond + "'";
            qro->exec(tmp_sq);
            qro->next();
            sq += " and clinic_code = '" + qro->value(0).toString() + "' ";
            qDebug()<<"通过个人编号查找clinic code"<<"\n";
        }
        else if(ui->cbb_cond->currentText() == "clinic_code")
        {
            cond = ui->leBzh->text().trimmed();
            sq += " and clinic_code = '" + cond + "' ";
        }
        else
        {
            QMessageBox::warning(this, "注意","限定条件无效！" );
            return;
        }

    }

    QString up_state = "'u'";

    if(ui->cbUnUpload->isChecked())
    {
        up_state += ",'0'";
    }

    if(ui->cbUploaded->isChecked())
    {
        up_state += ",'1'";
    }


    if( ui->rbMjzyb->isChecked() ){
        //门急诊医保
        sq += " and pact_code = '2' ";
        sq += " and upld_flg0 in(" + up_state + ") ";

        sq += " order by reg_date" ;

        qDebug()<<"检索门急诊数据 :"<<sq;
        qro->exec(sq);
        if(!qro->next()){
            QMessageBox::warning(NULL,"注意", "指定范围无数据 ！ " );
            mdList.setQuery("");
            ui->ptText->clear();
            return;
        }
    }

    if( ui->rbMjzzf->isChecked() ){
        //门急诊自费
        sq += " and pact_code = '1'  " ;

        sq += " and upld_flg0 in(" + up_state + ") ";

        sq += " order by reg_date";
        qDebug()<<"检索门急诊自费数据 :"<<sq;
        qro->exec(sq);
        if(!qro->next()){
            QMessageBox::warning(NULL,"注意", "指定范围无数据 ！ " );
            mdList.setQuery("");
            ui->ptText->clear();
            return;
        }
    }

    if( ui->rbZfsc->isChecked() ){
        //自费数据撤销
        sq += " and pact_code = '1'  and upld_flg0 = '1'  order by reg_date" ;

        qDebug()<<"检索门急诊自费数据 :"<<sq;
        qro->exec(sq);
        if(!qro->next()){
            QMessageBox::warning(NULL,"注意", "指定范围无数据 ！ " );
            mdList.setQuery("");
            ui->ptText->clear();
            return;
        }
    }

    if( ui->rbIcpc->isChecked() ){
        //icpc 筛选数据
        sq += " and pact_code = '2' ";
        sq += " and upld_flg1 in(" + up_state + ") ";
        sq += " order by reg_date" ;

        qDebug()<<"检索门急诊icpc数据 :"<<sq;
        qro->exec(sq);
        if(!qro->next()){
            QMessageBox::warning(NULL,"注意", "指定范围无数据 ！ " );
            mdList.setQuery("");
            ui->ptText->clear();
            return;
        }
    }

    mdList.setQuery(sq, pub::db_o);
    ui->tvList->setModel(&mdList);
    int w = ui->tvList->width();
    pub::setColumnWidth(ui->tvList, "0.2^0.2^0.18^0.15^0.2^0^0^0", w, 20);
}

void Form_dzbl::on_pbSingle_clicked()
{

    ui->ptText->clear();

    //ui->pbAll->setEnabled(false);
    ui->pbExit->setEnabled(false);
    ui->pbSearch->setEnabled(false);
    ui->pbSingle->setEnabled(false);
    qApp->processEvents();  //刷新显示

    if(ui->rbMjzyb->isChecked()){
        mjzyb(-1);  //门急诊医保
    }else if(ui->rbMjzzf->isChecked()){
        mjzzf(-1);  //门急诊自费
    }else if(ui->rbZfsc->isChecked()){
        zfsc(-1); //自费撤销
    }else if(ui->rbIcpc->isChecked()){
        icpc(-1);
    }else if(ui->rbJjjs->isChecked()){
        jjjs(); //医保结算清单
    }
    //ui->pbAll->setEnabled(true);
    ui->pbExit->setEnabled(true);
    ui->pbSearch->setEnabled(true);
    ui->pbSingle->setEnabled(true);

}


void Form_dzbl::on_pbAll_clicked()
{

    isAll = true;   //全部传输按钮标志

    ui->pbAll->setEnabled(false);
    ui->pbExit->setEnabled(false);
    ui->pbSearch->setEnabled(false);
    ui->pbSingle->setEnabled(false);

    qApp->processEvents();  //刷新显示

    int rowCount = mdList.rowCount() - 1; //行数 - 1 等于索引数
    while(rowCount >= 0){

        if(ui->rbMjzyb->isChecked()){  mjzyb(rowCount);}
        else if(ui->rbMjzzf->isChecked()){  mjzzf(rowCount);}
        else if(ui->rbIcpc->isChecked()){ icpc(rowCount);}

        rowCount--;
    }

    QMessageBox::information(this,"注意","全部数据操作完成。");
    //on_pbSearch_clicked();  // refresh display.

    ui->pbAll->setEnabled(true);
    ui->pbExit->setEnabled(true);
    ui->pbSearch->setEnabled(true);
    ui->pbSingle->setEnabled(true);

    isAll = false;

}

void Form_dzbl::on_pbExit_clicked()
{
    this->close();
}

/*
void Form_dzbl::getInformation(QString clinic_code)
{

    if(ui->rbMjzyb->isChecked()){ //门急诊医保
        patientInfo["adm_rec_no"] = clinic_code;
        sq = "select pact_name, dept_name, doct_name, oper_date from ";


    } else if ( ui->rbIcpc->isChecked()){

    }else if(ui->rbJjjs->isChecked()){

    }
    return;

    //以下暂时未用
    patientInfo["adm_rec_no"] = clinic_code;

    if(clinic_code.isEmpty()){
        QMessageBox::information(this,"注意","clinicCode 为空，无法检索病历!");
        return;
    }

    sq = "select v_out from com_business where clinic_code = '"
            + clinic_code +"' and ywbh = '1101' and v_out is not null order by jysj desc";
    qDebug()<<sq;
    qrm->exec(sq);
    qrm->next();

    QString js = qrm->value(0).toString();

    //QJsonDocument jsdc = QJsonDocument::fromJson(js.toLocal8Bit());
    QJsonDocument jsdc = QJsonDocument::fromJson(js.toUtf8());

    QJsonObject jsob = jsdc.object();

    personBaseinfo = jsob.value("output").toObject().value("baseinfo").toObject();
    personInsuinfo = jsob.value("output").toObject().value("insuinfo")[0].toObject();
    personIdetinfo = jsob.value("output").toObject().value("idetinfo")[0].toObject();

    qDebug()<<personBaseinfo;


    sq = "select v_in from com_business where clinic_code = '"
            + clinic_code +"' and ywbh = '2201' and v_in is not null order by jysj desc";
    qDebug()<<sq;
    qrm->exec(sq);
    qrm->next();

    js = qrm->value(0).toString();

    jsdc = QJsonDocument::fromJson(js.toUtf8());

    jsob = jsdc.object();
    qDebug()<<"jsob"<<jsob;
    person2201 = jsob.value("input").toObject().value("data").toObject();
    qDebug()<<"person2201"<<person2201;


    sq = "select v_in from com_business where clinic_code = '"
            + clinic_code +"' and ywbh = '2203A' and v_in is not null order by jysj desc";
    qDebug()<<sq;
    qrm->exec(sq);
    qrm->next();


    js = qrm->value(0).toString();
    qDebug()<<"js"<<js;
    //jsdc = QJsonDocument::fromJson(js.toLocal8Bit());
    jsdc = QJsonDocument::fromJson(js.toUtf8());

    jsob = jsdc.object();

    person2203 = jsob.value("input").toObject().value("mdtrtinfo").toObject();
    person2203a = jsob.value("input").toObject().value("diseinfo").toArray();
    qDebug()<<"person2203"<<person2203;
    qDebug()<<"person2203a"<<person2203a;



    sq = "select v_out from com_business where clinic_code = '"
            + clinic_code +"' and ywbh = '2207A' and v_out is not null order by jysj desc";
    qDebug()<<sq;
    qrm->exec(sq);
    qrm->next();

    js = qrm->value(0).toString();

    jsdc = QJsonDocument::fromJson(js.toUtf8());

    jsob = jsdc.object().value("output").toObject();

    person2207 = jsob.value("setlinfo").toObject();

    qDebug()<<"person2207"<<person2207;

    QMap<QString, QString> pageInfo;
    sq = "select name, sex_code, to_char(birthday,'yyyyMMdd') birth,to_char( reg_date,'yyyy-mm-dd')reg_dt, "
         "dept_name, mcard_no , card_no "
         " from fin_opr_register"
         " where clinic_code = '" + clinic_code + "'";
    qro->exec(sq);
    qro->next();
    patientInfo["name"] = pageInfo["name"] = qro->value(0).toString();
    patientInfo["gend"] = pageInfo["sex"] = qro->value(1).toString() == "M" ? "男" : "女";
    patientInfo["birth"] = pageInfo["birth"] = qro->value(2).toString() ;
    patientInfo["adm_time"] = pageInfo["regdt"] = qro->value(3).toString() ;
    patientInfo["dept_name"] = pageInfo["dpnm"] = qro->value(4).toString() ;
    pageInfo["mcard_no"] = qro->value(5).toString() ;
    patientInfo["mdtrt_sn"] = pageInfo["card_no"] = qro->value(6).toString() ;
    patientInfo["mdtrtsn"] = patientInfo["mdtrt_sn"] ;
    qDebug()<<"检索医师处方内容";
    QString cur_date, cur_bzh;
    sq="select FEE_CODE,recipe_no,charge_flag,CLINIC_CODE,CARD_NO,to_char(REG_DATE,'yyyy-mm-dd') cdt ,ITEM_CODE,ITEM_NAME,"
       "SPECS,DRUG_FLAG,CLASS_CODE,QTY,ITEM_UNIT,ONCE_DOSE,ONCE_UNIT,FREQUENCY_NAME,USAGE_NAME,EXEC_DPNM,DOCT_NAME,LAB_TYPE,"
       "CHECK_BODY,CLINICDIAG_CODE,CLINICDIAG_NAME,CLINICOTHERDIAG1_CODE,CLINICOTHERDIAG1_NAME,CLINICOTHERDIAG2_CODE,"
       "CLINICOTHERDIAG2_NAME "
       " from met_ord_recipedetail "
       " where clinic_code = '"
            + clinic_code + "' and DRUG_FLAG <> '2' and status = '1' ";
    sq += " order by drug_flag, oper_date";
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error", qro->lastError().text());
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
        return;
    }
    if(!qro->next()){
        QMessageBox::information(this,"error", "找不到指定检索信息关联的医师处方内容！");
        qDebug()<<qro->lastQuery();
        return;
    }
    pageInfo["cur_date"] = qro->value("cdt").toString();
    pageInfo["cur_bzh"] = qro->value("CARD_NO").toString();
    pageInfo["jzys"] = qro->value("DOCT_NAME").toString();

    while(true){
        //首先检查处方是否执行，然后检查是否退费
        pageInfo["zd"] = qro->value("CLINICDIAG_NAME").toString();
        if(!qro->value("CLINICOTHERDIAG1_NAME").toString().isEmpty()){
            pageInfo["zd"].append("^"+qro->value("CLINICOTHERDIAG1_NAME").toString());
        }
        if(!qro->value("CLINICOTHERDIAG2_NAME").toString().isEmpty()){
            pageInfo["zd"].append("^"+qro->value("CLINICOTHERDIAG2_NAME").toString());
        }
        QString s;
        s = qro->value("charge_flag").toString();
        if(s == "0"){
            s = "（未执行）";
        }else{
            sq=" select count(*) c from pha_com_output where recipe_no = "
               "'"+qro->value("recipe_no").toString()+"' and return_num >0";
            qrot->exec(sq);
            qrot->next();
            if(qrot->value(0).toInt() > 0){
                s = "（已退费）";
            }else{
                s = "";
            }
        }
        int fee_code = qro->value("fee_code").toInt();
        //1 西药 ， 2 中药
        //4 化验 ，7 检查
        //5 处置，
        // 6 留观费 ，10 器械
        //11 采血费， 12 彩色打印照片, 14 取暖费 ，22 床位费（床）

        if( fee_code == 1 || fee_code == 2){ //药品
            s.append(qro->value("ITEM_NAME").toString());
            s.append(" ");
            s.append(qro->value("SPECS").toString());
            s.append(qro->value("QTY").toString());
            s.append(qro->value("ITEM_UNIT").toString());
            s.append("  ");
            s.append(qro->value("USAGE_NAME").toString());
            s.append(" ");
            s.append(qro->value("ONCE_DOSE").toString());
            s.append(qro->value("ONCE_UNIT").toString());
            s.append("/");
            s.append(qro->value("FREQUENCY_NAME").toString());
            if(pageInfo["cljg"].isEmpty()){
                pageInfo["cljg"].append(s);
            }else{
                pageInfo["cljg"].append("\r\n" + s);
            }
        }else if( fee_code == 4 || fee_code == 7){ //化验，检查
            s.append(qro->value("ITEM_NAME").toString());
            s.append(" ");
            s.append(qro->value("QTY").toString());
            s.append(qro->value("ITEM_UNIT").toString());
            if(pageInfo["jcjg"].isEmpty()){
                pageInfo["jcjg"].append(s);
            }else{
                pageInfo["jcjg"].append("\r\n" + s);
            }
        }else if( fee_code == 5){ //处置
            s.append(qro->value("ITEM_NAME").toString());
            s.append(" ");
            s.append(qro->value("QTY").toString());
            s.append(qro->value("ITEM_UNIT").toString());
            if(pageInfo["cljg"].isEmpty()){
                pageInfo["cljg"].append(s);
            }else{
                pageInfo["cljg"].append("\r\n" + s);
            }
        }

        if(!qro->next()){
            break;
        }
    }

    sq="select r.hzzs,r.xbs,r.jws,r.tgjc,r.yz,r.ys ,r.atinc , r.gms ,r.zd1,r.zd2,r.zd3"
       " from ys_bz_e_rec r "
       " where clinic_code = '" + clinic_code + "'";
    qrm->exec(sq);
    if(qrm->next())
    {
        patientInfo["hzzs"] = pageInfo["hzzs"] = qrm->value("hzzs").toString();
        patientInfo["xbs"] = pageInfo["xbs"] = qrm->value("xbs").toString();
        patientInfo["jws"] = pageInfo["jws"] = qrm->value("jws").toString();
        patientInfo["gms"] = pageInfo["gms"] = qrm->value("gms").toString();
        patientInfo["zzms"] = pageInfo["zzms"] = qrm->value("tgjc").toString();
        patientInfo["yz"] = pageInfo["yz"] = qrm->value("yz").toString();
        patientInfo["lxdh"] = pageInfo["lxdh"] = qrm->value("lxdh").toString();

    }
    else
    {
        pageInfo["hzzs"] = "";
        pageInfo["xbs"] = "";
        pageInfo["jws"] = "";
        pageInfo["gms"] = "";
        pageInfo["zzms"] = "";
        pageInfo["yz"] = "";

    }

    QString item;

    QStringList ageList = pub::getNl(pageInfo["birth"]);

    item = "姓名：" + pageInfo["name"] + "\t性别："
            + pageInfo["sex"] + "\t年龄：" + ageList[0]+ageList[1] + "\n";
    ui->ptText->insertPlainText( item );

    item = "病志号：" + pageInfo["card_no"] + "\n就诊日期：" + pageInfo["regdt"] + "\n";
    ui->ptText->insertPlainText( item);

    item = "诊室：" + pageInfo["dpnm"] + "\t医保卡号：" + pageInfo["mcard_no"]  + "\n";
    ui->ptText->insertPlainText( item);


    item = "患者主诉：" +  pageInfo["hzzs"] + "\n";
    ui->ptText->insertPlainText( item);

    item = "现病史：" + pageInfo["xbs"] + "\n";
    ui->ptText->insertPlainText( item);

    item = "既往史：" + pageInfo["jws"]  + "\n";
    ui->ptText->insertPlainText( item);

    item = "过敏史：" + pageInfo["gms"]  + "\n";
    ui->ptText->insertPlainText( item);

    item = "专科检查：" + pageInfo["zzms"]  + "\n";
    ui->ptText->insertPlainText( item);

    item = "化验检查：" + pageInfo["jcjg"] + "\n";
    ui->ptText->insertPlainText( item);

    item = "诊断：" + pageInfo["zd"]  + "\n";
    item.replace("^","，");
    ui->ptText->insertPlainText( item);

    item = "处置：" +  pageInfo["cljg"] + "\n";
    ui->ptText->insertPlainText( item);

    item = "主治医生：" +  pageInfo["jzys"] + "\n";
    ui->ptText->insertPlainText( item);


}
*/

void Form_dzbl::icpc(int currentRow)
{
    //ICPC信息
    //2024-10-31 修改处方提取sql，适应医保挂号现金收费修改

    logFile->open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(logFile);

    qApp->processEvents();  //刷新显示
    QString clinic_code, card_no, reg_date, dept_code, dept_name ;
    QString rowid, psn_no, invo_no, ynfr, mdtrt_id,setl_id;
    QString reg_invoice_no, reg_dt_icpc, reg_fee_code_center,reg_fee_code_his,reg_icpc_code;

    if(currentRow < 0)  {   //单个上传
        clinic_code = mdList.record(ui->tvList->currentIndex().row()).value(5).toString();
        card_no = mdList.record(ui->tvList->currentIndex().row()).value(2).toString();
        reg_date = mdList.record(ui->tvList->currentIndex().row()).value(0).toString();
        dept_code = mdList.record(ui->tvList->currentIndex().row()).value(9).toString();
        dept_name = mdList.record(ui->tvList->currentIndex().row()).value(4).toString();
        rowid = mdList.record(ui->tvList->currentIndex().row()).value(10).toString();
        //idenno = mdList.record(ui->tvList->currentIndex().row()).value(18).toString();
        invo_no = mdList.record(ui->tvList->currentIndex().row()).value(17).toString();
        ynfr = mdList.record(ui->tvList->currentIndex().row()).value(18).toString();

    }else{ //批量上传

        //QMessageBox::information(this,"Note",QString::number(currentRow));
        clinic_code = mdList.record(currentRow).value(5).toString();
        card_no = mdList.record(currentRow).value(2).toString();
        reg_date = mdList.record(currentRow).value(0).toString();
        dept_code = mdList.record(currentRow).value(9).toString();
        dept_name = mdList.record(currentRow).value(4).toString();
        rowid = mdList.record(currentRow).value(10).toString();
        //idenno = mdList.record(currentRow).value(18).toString();
        invo_no = mdList.record(currentRow).value(17).toString();
        ynfr = mdList.record(currentRow).value(18).toString();

    }

    sq = " select ipr.mdtrt_id, ipr.psn_no, ipr.setl_id ,"
         " reg.invoice_no , to_char(reg.reg_date,'yyyy-mm-dd hh24:mi:ss') rgdt,"
         " regfee.fee_code_center , regfee.fee_code_his, regfee.icpc_code"
         " from fin_ipr_siinmaininfo ipr"
         " left join fin_opr_register reg on reg.clinic_code = ipr.inpatient_no "
         " left join FIN_OPR_REGFEEITEM regfee on regfee.reg_level = reg.reglevl_code"
         " where "
         " reg.trans_type = '1' and "
         " ipr.balance_no = '0' and "
         " ipr.inpatient_no = '" + clinic_code + "'"; // and invoice_no = '" + invo_no + "'
    qrot->exec(sq);
    qDebug()<<"提取挂号相关信息："<<sq;

    if(!qrot->next())
    {
        ui->ptText->appendPlainText("病志号 " + card_no + ", "+ "提取医保结算ID失败！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " icpc : "<< "病志号 " + card_no + ", "+ "提取医保结算ID失败！" << "\r\n";
        logFile->flush();
        logFile->close();
        return;
    }

    mdtrt_id = qrot->value("mdtrt_id").toString();
    psn_no = qrot->value("psn_no").toString();
    setl_id = qrot->value("setl_id").toString();
    reg_invoice_no = qrot->value("invoice_no").toString();
    reg_dt_icpc = qrot->value("rgdt").toString();
    reg_fee_code_center = qrot->value("fee_code_center").toString();
    reg_fee_code_his = qrot->value("fee_code_his").toString();
    reg_icpc_code = qrot->value("icpc_code").toString();

    ui->ptText->appendPlainText("病志号 " + card_no + " 开始数据传输...");
    qApp->processEvents();  //刷新显示

    //提取挂号信息
    if( !isAll ){
        ui->ptText->appendPlainText("病志号 " + card_no + ", " + mdList.record(currentRow).value(2).toString()+ " 提取挂号信息...");
        qApp->processEvents();  //刷新显示
    }

    QJsonObject in;   //医保交易入参信息
    QJsonObject inpu1; //挂号及就诊信息（节点标识：rgstinfo）
    QJsonArray inpu2;   //就诊原因信息（节点标识：mdtrtreainfo）
    QJsonArray inpu3;   //疾病诊断信息（节点标识：diseinfo）
    QJsonArray inpu4;   //检查治疗编码及处方信息（节点标识：rxinfo）
    QJsonObject t2,t3,t4;   //临时周转信息使用

    //挂号及就诊信息（节点标识：rgstinfo）
    inpu1.insert("mdtrt_sn", clinic_code); //就医流水号	字符型	30		Y	院内唯一号
    inpu1.insert("mdtrt_id", mdtrt_id);//	就诊ID	字符型	30		Y
    inpu1.insert("psn_no", psn_no);//	人员编号	字符型	30		Y
    inpu1.insert("vali_flag", "1");//	有效标志	字符型	3	Y　	Y
    inpu1.insert("setl_id", setl_id);//	结算ID	字符型	30	　	Y
    inpu1.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型	12		Y
    inpu1.insert("arch_flag", "1");//	就诊结束标志	字符型	3	Y	Y	0-未结束、1-已结束
    //inpu1.insert("arch_time", idenno);//	就诊结束时间	日期时间型
    inpu1.insert("mdtrt_fee_end_flag", "1");//	就诊费用结束标志	字符型	3	Y	Y	0-未结束、1-已结束
    inpu1.insert("fstdiag_flag", ynfr);//	初诊标志	字符型	3	Y	Y	0-否、1-是

    //就诊原因信息（节点标识：mdtrtreainfo）

    sq="select jzyy, jzyyc, zd1, zd1c, zd2, zd2c, zd3, zd3c "
       "from ys_bz_e_rec a where clinic_code = '" + clinic_code + "'";//, com_dict_icpc b

    qrm->exec(sq);
    if(!qrm->next()){
        ui->ptText->appendPlainText(" 无关联病历信息。");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " icpc : "<< "病志号 " + card_no + ", "+ " 无关联病历信息。！" << "\r\n";
        logFile->flush();
        logFile->close();
        return;
    }
    QString jzyy = qrm->value("jzyy").toString();
    QString jzyyc = qrm->value("jzyyc").toString();

    if(jzyy.isEmpty() || jzyyc.isEmpty())
    {
        ui->ptText->appendPlainText("  缺失就诊原因或主诊断。");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " icpc : "<< "病志号 " + card_no + ", "+ "缺失就诊原因或主诊断！" << "\r\n";
        logFile->flush();
        logFile->close();
        return;
    }

    t2.insert("mdtrt_rea_name", jzyy);  //就诊原因名称	字符型	2000		Y	上传临床填写名称
    t2.insert("mdtrt_rea_code", jzyyc);  //就诊原因编码	字符型	100		Y	上传ICPC编码
    //reg_jzyy = qrm->value("jzyyc").toString();
    t2.insert("main_mdtrt_rea","1");//	主要就诊原因	字符型	3	Y	Y	1-是 0-否
    t2.insert("vali_flag","1");//	有效标志	字符型	3	Y	Y
    inpu2 << t2;

    //疾病诊断信息（节点标识：diseinfo）
    qrmt->exec("select icpc_code, icpc_name from com_dict_icpc  "
               " where valid_flag = '1' "
               " and  nat_code = '" + qrm->value("zd1c").toString() + "'");
    if(!qrmt->next())
    {
        ui->ptText->appendPlainText("找不到诊断 " + qrm->value("zd1").toString() + " 国标编码关联的ICPC编码！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " icpc : "
                    << "病志号 " + card_no + ", 找不到诊断 " + qrm->value("zd1").toString() + " 国标编码关联的ICPC编码！"
                    << "\r\n";
        logFile->flush();
        logFile->close();
        return;
    }

    if(qrmt->value(0).toString() == "0")
    {
        ui->ptText->appendPlainText("ICPC编码为 0 ！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " icpc : "
                    << "病志号 " + card_no + ", "+ " icpc 编码为0！ "
                    << "\r\n";
        logFile->flush();
        logFile->close();
        return;
    }

    t3.insert("dise_code", qrmt->value("icpc_code").toString() );  //疾病诊断编码	字符型	100	Y		上传ICPC编码
    t3.insert("dise_name",  qrmt->value("icpc_name").toString());  //疾病诊断名称	字符型	2000			上传临床填写名称

    t3.insert("main_disediag_flag","1"); //	主要疾病诊断标识	字符型	3	Y		1-是 0-否
    t3.insert("vali_flag","1"); //	有效标志	字符型	3	Y	Y
    inpu3 << t3;

    if(!qrm->value("zd2").isNull() && !qrm->value("zd2").toString().isEmpty())
    {
        qrmt->exec("select icpc_code,icpc_name from com_dict_icpc  "
                   " where valid_flag = '1' "
                   " and  nat_code ='" + qrm->value("zd2c").toString() + "' ");
        if(!qrmt->next())
        {
            ui->ptText->appendPlainText("找不到诊断 " + qrm->value("zd2").toString() + " 国标编码关联的ICPC编码！");
            text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                        << " icpc : "
                        << "病志号 " + card_no + ", 找不到诊断 " + qrm->value("zd2").toString() + " 国标编码关联的ICPC编码！"
                        << "\r\n";
            logFile->flush();
            logFile->close();
            return;
        }
        if(qrmt->value(0).toString() != "0")
        {
            t3.insert("dise_code",  qrmt->value("icpc_code").toString());  //疾病诊断编码	字符型	100	Y		上传ICPC编码
            t3.insert("dise_name",  qrmt->value("icpc_name").toString());  //疾病诊断名称	字符型	2000			上传临床填写名称
            t3.insert("main_disediag_flag","0"); //	主要疾病诊断标识	字符型	3	Y		1-是 0-否
            t3.insert("vali_flag","1"); //	有效标志	字符型	3	Y	Y
            inpu3 << t3;
        }
    }

    if(!qrm->value("zd3").isNull() && !qrm->value("zd3").toString().isEmpty())
    {
        qrmt->exec("select icpc_code from com_dict_icpc  "
                   " where valid_flag = '1' "
                   " and  nat_code ='" + qrm->value("zd3c").toString() + "' ");
        if(!qrmt->next())
        {
            ui->ptText->appendPlainText("找不到诊断 " + qrm->value("zd3").toString() + " 国标编码关联的ICPC编码！");
            text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                        << " icpc : "
                        << "病志号 " + card_no + ", 找不到诊断 " + qrm->value("zd3").toString() + " 国标编码关联的ICPC编码！"
                        << "\r\n";
            logFile->flush();
            logFile->close();
            return;
        }
        if(qrmt->value(0).toString() != "0")
        {
            t3.insert("dise_code",  qrmt->value("icpc_code").toString());  //疾病诊断编码	字符型	100	Y		上传ICPC编码
            t3.insert("dise_name",  qrmt->value("icpc_name").toString());  //疾病诊断名称	字符型	2000			上传临床填写名称
            t3.insert("main_disediag_flag","0"); //	主要疾病诊断标识	字符型	3	Y		1-是 0-否
            t3.insert("vali_flag","1"); //	有效标志	字符型	3	Y	Y
            inpu3 << t3;
        }
    }

    //检查治疗编码及处方信息（节点标识：rxinfo）

    //挂号
    bool all_empty = true;
    if(!reg_fee_code_center.isEmpty())
    {
        //上传结点非全空
        all_empty = false;
        //t4.insert("feedetl_sn", reg_invoice_no);//费用明细流水号	字符型	30	　	Y
        t4.insert("feedetl_sn", "0");//费用明细流水号	字符型	30	　	Y
        t4.insert("rx_prsc_time", reg_dt_icpc);//处方开方时间	日期时间型			Y
        t4.insert("vali_flag", "1");//	有效标志	字符型	3	Y　	Y
//        t4.insert("hosp_dise", reg_fee_code_center);//检查及治疗编码	上传ICPC检查治疗编码
        t4.insert("hosp_dise", reg_icpc_code);//检查及治疗编码	上传ICPC检查治疗编码
//        t4.insert("med_list_codg", reg_fee_code_his);//	医疗目录编码	字符型	50	　	Y
        t4.insert("med_list_codg", reg_fee_code_center);//	医疗目录编码	字符型	50	　	Y
        t4.insert("drord_diag_code", jzyyc);//上传ICPC就诊原因及疾病编码

        inpu4 << t4;
    }
    else
    {
        ui->ptText->appendPlainText("找不到有效的挂号诊查费！");
    }
    //处方部分
    sq = "select sequence_no, "
         " to_char(oper_date,'yyyy-mm-dd hh24:mi:ss'), "
         " item_code , "
         " clinicdiag_code, "
         " item_name，"
         " clinicdiag_name "
         " from met_ord_recipedetail met"
         " where "
         " charge_flag = '1' "  //缴费
         " and status <>'3' "   //作废
         " and status <>'4' "   //撤销
         " and recipe_no in "
         "   ( select distinct a.recipe_no "
         "     from fin_opb_feedetail a, fin_opb_invoiceinfo b"
         "     where "
         "     a.invoice_no = b.invoice_no "
         "     and b.clinic_code = '%1' "
         "     and b.paykind_code = '02' "
         "    ) "
         " and recipe_no not in "
         "    ( select recipe_no "
         "      from fin_opb_insu_cash ic "
         "      where ic.mo_order = met.sequence_no "
         "    )"
         " order by oper_date";

    sq = sq.arg(clinic_code);



    qDebug()<<"icpc 上传检索处方内容："<<sq;

    if(!qro->exec(sq))
    {
        QMessageBox::information(this, "注意", "检索医师处方失败！\nerrmsg : " + qro->lastError().text()+"\nsql : "+sq);
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " icpc : 病志号 " + card_no + ", 检索医师处方失败！\r\n";
        logFile->flush();
        logFile->close();
        return;
    }

    bool has_recipe = true;

    if(!qro->next())
    {
        ui->ptText->appendPlainText(" 找不到有效的医师处方内容！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " icpc : 病志号 " + card_no + ", "+ "找不到有效的医师处方内容！\r\n";
        logFile->flush();
        logFile->close();
        has_recipe = false;
        //return;
    }

    if(has_recipe)
    {

    while(true)
    {
        t4.insert("feedetl_sn", qro->value(0).toString());//费用明细流水号	字符型	30	　	Y
        t4.insert("rx_prsc_time", qro->value(1).toString());//	处方开方时间	日期时间型			Y
        t4.insert("vali_flag", "1");//	有效标志	字符型	3	Y　	Y

        qrmt->exec("select icpc_code,nat_code from com_dict_icpc  "
                   " where valid_flag = '1' "
                   " and  item_code = '"
                   + qro->value(2).toString() + "'");

        qDebug()<<"检索院内项目icpc编码："<<"select icpc_code,nat_code from com_dict_icpc where item_code = '"+qro->value(2).toString()+"'\n";

        if(!qrmt->next()
                || qrmt->value(0).toString() == "0")
        {
            //查不到，或查到结果为 0
            ui->ptText->appendPlainText("找不到院内项目 " + qro->value(4).toString()
                                        + "/" + qro->value(2).toString() + " 关联的ICPC编码！");
            if(!qro->next())
            {
                //医保患者使用非医保对照品种
                break;
            }
            continue;
            //return;
        }

        if(qrmt->value(1).toString().isEmpty())
        {
            ui->ptText->appendPlainText("医疗目录编码为空, 院内编码: " + qro->value(2).toString());
            text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                        << " icpc : "
                        << "病志号 " + card_no + ", 医疗目录编码为空，院内编码： " + qro->value(2).toString()<< "\r\n";
            logFile->flush();
            logFile->close();
            return;
        }

        t4.insert("hosp_dise", qrmt->value(0).toString());//检查及治疗编码	上传ICPC检查治疗编码
        t4.insert("med_list_codg", qrmt->value(1).toString());//	医疗目录编码	字符型	50	　	Y
        qrmt->exec("select icpc_code from com_dict_icpc  "
                   " where valid_flag = '1' "
                   " and  nat_code = '"
                   + qro->value(3).toString() + "'");

        if(!qrmt->next())
        {
            ui->ptText->appendPlainText("找不到诊断 " + qro->value(5).toString()
                                        +"/" + qro->value(3).toString() + " 关联的ICPC编码！");
            text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                        << " icpc : "
                        << "病志号 " + card_no + ", 找不到诊断 " + qro->value(5).toString()
                        << "/" + qro->value(3).toString() + " 关联的ICPC编码！"
                        << "\r\n";
            logFile->flush();
            logFile->close();
            return;
        }

        t4.insert("drord_diag_code", qrmt->value(0).toString());//上传ICPC就诊原因及疾病编码
        //t4.insert("med_list_codg", qro->value(3).toString());//	医疗目录编码	字符型	50	　	Y

        inpu4 << t4;

        if(!qro->next()){
            break;
        }

    }

    }

    if(inpu4.size() == 0)
    {
        ui->ptText->appendPlainText("患者未发生医保费用，无需上传！ ");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " icpc : "
                    << "病志号 " + card_no + ", 处方结点为空！ \r\n";
        logFile->flush();
        logFile->close();
        return;
    }
    else
    {
        all_empty = false;
    }

//    if(all_empty)
//    {
//        //无数据可传
//        QMessageBox::information(this, "注意", "患者无医保费用发生，无需上传!");
//        return;
//    }

    in.insert("rgstinfo",inpu1);
    in.insert("mdtrtreainfo",inpu2);
    in.insert("diseinfo",inpu3);
    in.insert("rxinfo",inpu4);

    text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                << " 4361 : "<<QJsonDocument(in).toJson() << "\r\n";

    if(call_noRet("4361",in, clinic_code))
    {
        ui->ptText->appendPlainText("病志号 " + card_no + " 数据传输成功。");
        qrot->exec( "update fin_opr_register set upld_flg1 = '1' where rowid = '" + rowid + "'") ;
    }
    else
    {
        ui->ptText->appendPlainText("   病志号 " + card_no + " 数据传输失败。");
        text_stream << "   病志号 " + card_no + " 数据传输失败。";
    }

    qApp->processEvents();  //刷新显示
    logFile->flush();
    logFile->close();
}

void Form_dzbl::jjjs()
{
    QJsonObject in;
    if(!putBaseIn(  in, "4101") ){
        return;
    }
    QJsonDocument d;

    QJsonObject inpu,inpud;

    //setlinfo
    inpu.insert("mdtrt_id", person2207.value("mdtrt_id").toString());//就诊ID字符型30Y
    inpu.insert("setl_id", person2207.value("setl_id").toString());//结算ID字符型30Y
    inpu.insert("fixmedins_name", pub::hos_name);//定点医药机构名称字符型200Y
    inpu.insert("fixmedins_code", pub::hos_ybbh);//定点医药机构编号字符型12Y
    inpu.insert("medcasno", patientInfo["mdtrt_sn"]);//病案号字符型40Y
    qDebug()<<"patientInfo[card_no]"<<patientInfo["mdtrt_sn"];
    inpu.insert("psn_name", patientInfo["name"]);//人员姓名字符型50Y
    inpu.insert("gend", personBaseinfo.value("gend").toString());//性别字符型6YY
    inpu.insert("brdy", personBaseinfo.value("brdy").toString());//出生日期日期型Y
    inpu.insert("age", personBaseinfo.value("age").toDouble());//
    inpu.insert("ntly", "CN");//国籍字符型6YY
    inpu.insert("naty", personBaseinfo.value("naty").toString());//民族字符型3YY
    inpu.insert("patn_cert_type", personBaseinfo.value("psn_cert_type").toString());//患者证件类别字符型3YY
    inpu.insert("certno", personBaseinfo.value("certno").toString());//证件号码字符型50Y
    inpu.insert("prfs", "90");//职业字符型6Y　Y
    inpu.insert("coner_name", patientInfo["name"]);//联系人姓名字符型50Y
    inpu.insert("patn_rlts", "01");//与患者关系字符型6Y　Y
    inpu.insert("coner_addr", "0");//联系人地址字符型200Y
    inpu.insert("coner_tel", "13511112222");//联系人电话字符型50Y
    inpu.insert("hi_type", "310");//医保类型字符型3Y　Y
    inpu.insert("insuplc", personInsuinfo.value("insuplc_admdvs").toString());//参保地字符型6Y
    inpu.insert("ipt_med_type", "");//住院医疗类型字符型3Y　Y
    inpu.insert("adm_caty", "");//入院科别字符型6Y　Y
    inpu.insert("refldept_dept", "");//转科科别字符型6Y
    inpu.insert("dscg_caty", "");//出院科别字符型6Y　Y
    inpu.insert("maindiag_flag", "");//主诊断标志字符型3YY
    inpu.insert("bill_code","111");//票据代码字符型50Y
    inpu.insert("bill_no","002");//票据号码字符型30Y
    inpu.insert("biz_sn","001");//业务流水号字符型50Y
    inpu.insert("setl_begn_date", person2207.value("setl_time").toString());//结算开始日期日期型Y
    inpu.insert("setl_end_date", person2207.value("setl_time").toString());//结算结束日期日期型Y
    inpu.insert("psn_selfpay",  0);//个人自付数值型16,2Y
    inpu.insert("psn_ownpay", 0);//个人自费数值型16,2Y
    inpu.insert("acct_pay", 0);//个人账户支出数值型16,2Y
    inpu.insert("psn_cashpay", 0);//个人现金支付数值型16,2Y
    inpu.insert("hi_paymtd", "1");//医保支付方式字符型3Y　Y
    inpu.insert("hsorg", "");//医保经办机构字符型100Y
    inpu.insert("hsorg_opter", "");//医保机构经办人字符型50Y
    inpu.insert("medins_fill_dept", "沈阳和平仁晟门诊部");//定点医疗机构填报部门字符型100Y
    inpu.insert("medins_fill_psn", "测试");//定点医疗机构填报人字符型50Y

    inpud.insert("setlinfo",inpu);




    //payinfo
    inpu = d.object();
    QJsonArray jsarPayinfo;

    inpu.insert("fund_pay_type", "310100");//基金支付类型字符型6　Y　Y
    inpu.insert("fund_payamt", 10);//基金支付金额数值型16,2　Y


    jsarPayinfo<<inpu;

    inpud.insert("payinfo", jsarPayinfo);

    //iteminfo收费项目
    inpu = d.object();
    QJsonArray jsarIteminfo;

    inpu.insert("med_chrgitm", "09");//医疗收费项目字符型6YY
    inpu.insert("amt", 10);//金额数值型16,2Y
    inpu.insert("claa_sumfee", 10);//甲类费用合计数值型16,2Y
    inpu.insert("clab_amt", 0);//乙类金额数值型16,2Y
    inpu.insert("fulamt_ownpay_amt", 0);//全自费金额数值型16,2Y
    inpu.insert("oth_amt", 0);//其他金额数值型16,2Y

    jsarIteminfo<<inpu;

    inpud.insert("iteminfo", jsarIteminfo);

    /*
    //opspdiseinfo门慢
    inpu.insert("参数代码","");//参数名称参数类型参数长度代码标识是否必填
    inpu.insert("diag_name","");//病种名称字符型100Y
    inpu.insert("diag_code","");//病种代码字符型20Y
    inpu.insert("oprn_oprt_name","");//手术操作名称字符型500Y
    inpu.insert("oprn_oprt_code","");//手术操作代码字符型30Y
    inpu.insert("maindiag_flag","");//主诊断标志字符型3YY

    //diseinfo住院
    inpu.insert("diag_type","");//诊断类别字符型3　Y　Y
    inpu.insert("diag_code","");//诊断代码字符型20　Y
    inpu.insert("diag_name","");//诊断名称字符型100　Y
    inpu.insert("maindiag_flag","");//主诊断标志字符型3YY


    //oprninfo手术
    inpu.insert("oprn_oprt_type","");//手术操作类别字符型3YY
    inpu.insert("oprn_oprt_name","");//手术操作名称字符型500Y
    inpu.insert("oprn_oprt_code","");//手术操作代码字符型30Y
    inpu.insert("oprn_oprt_date","");//手术操作日期日期型Y
    inpu.insert("anst_way","");//麻醉方式字符型6Y
    inpu.insert("oper_dr_name","");//术者医师姓名字符型50Y
    inpu.insert("oper_dr_code","");//术者医师代码字符型20Y
    inpu.insert("oprn_oprt_begnendtime","");//手术及操作起止时间日期型Y
    inpu.insert("anst_begnendtime","");//麻醉起止时间日期型Y

    //icuinfoicu
    inpu.insert("scs_cutd_ward_type","");//重症监护病房类型字符型6YY
    inpu.insert("scs_cutd_inpool_time","");//重症监护进入时间日期时间型Y
    inpu.insert("scs_cutd_exit_time","");//重症监护退出时间日期时间型Y
    inpu.insert("scs_cutd_sum_dura","");//重症监护合计时长字符型10Y
*/
    //inpud.insert()
    //    in.insert("input", inpud);

    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    qDebug()<<"4101 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。


    qDebug()<<" request 4101 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        return ;
    }


    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());

        return ;
    }
    qDebug()<< "4101 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set  tmstmp = now(), v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  "  where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }


    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","4101 交易失败：" + t );

        return ;
    }

    QMessageBox::information(this,"注意","结算信息上传完成。");

}

bool Form_dzbl::putBaseIn( QJsonObject &in, QString code)
{
    QString inp;
    inp = pub::getYbStrJ(code,"");   //
    if(inp.isEmpty()){
        //pub::useInsurance = false;  //设置医保不可用
        QMessageBox::information(this,"note","申请交易流水号失败！");
        return false; //未能成功申请交易流水号
    }

    currentMsgid = inp;

    in.insert("infno", code);
    in.insert( "msgid", inp);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);
    //in.insert("insuplc_admdvs", mpPerson["insuplc_admdvs"] );

    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

    return true;
}

void Form_dzbl::on_cbUnUpload_clicked()
{
    //ui->cbUnUpload->setChecked(true);
    //ui->cbSingle->setChecked(false);
    mdList.setQuery("");
    if(ui->cbUnUpload->isChecked())
    {
        if(ui->cbSingle->isChecked())
        {
            ui->pbSingle->setEnabled(false);
            ui->pbAll->setEnabled(false);
        }else{
            ui->pbSingle->setEnabled(true);
            ui->pbAll->setEnabled(true);
        }
    }else{
        ui->pbSingle->setEnabled(false);
        ui->pbAll->setEnabled(false);
    }

}

void Form_dzbl::on_cbSingle_clicked()
{
    //ui->cbUnUpload->setChecked(false);
    //ui->cbSingle->setChecked(true);
    if(ui->cbSingle->isChecked())
    {
        ui->pbSingle->setEnabled(false);
        ui->pbAll->setEnabled(false);
    }else{
        if(ui->cbUnUpload->isChecked())
        {
            ui->pbSingle->setEnabled(true);
            ui->pbAll->setEnabled(true);
        }else{
            ui->pbSingle->setEnabled(false);
            ui->pbAll->setEnabled(false);
        }
    }
}


void Form_dzbl::zfsc(int currentRow)
{
    //医保门急诊患者信息
    qApp->processEvents();  //刷新显示
    QString clinic_code, card_no, reg_date, dept_code, dept_name , rowid ;

    if(currentRow < 0)  {   //单个
        clinic_code = mdList.record(ui->tvList->currentIndex().row()).value(5).toString();
        card_no = mdList.record(ui->tvList->currentIndex().row()).value(2).toString();
        reg_date = mdList.record(ui->tvList->currentIndex().row()).value(0).toString();
        dept_code = mdList.record(ui->tvList->currentIndex().row()).value(9).toString();
        dept_name = mdList.record(ui->tvList->currentIndex().row()).value(4).toString();
        rowid = mdList.record(ui->tvList->currentIndex().row()).value(10).toString();

    }else{ //批量上传

        //QMessageBox::information(this,"Note",QString::number(currentRow));
        clinic_code = mdList.record(currentRow).value(4).toString();
        card_no = mdList.record(currentRow).value(1).toString();
        reg_date = mdList.record(currentRow).value(0).toString();
        dept_code = mdList.record(currentRow).value(8).toString();
        dept_name = mdList.record(currentRow).value(3).toString();
        rowid = mdList.record(currentRow).value(9).toString();
    }

    ui->ptText->appendPlainText(" 数据准备完成，开始传输...");
    qApp->processEvents();  //刷新显示

    QJsonObject in;
    in.insert("fixmedins_mdtrt_id", clinic_code);//	医药机构就诊ID	字符型
    in.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型

    if(call_noRet("4206",in, clinic_code))
    {
        qrot->exec( "update fin_opr_register set upld_flg0 = '0' where rowid = '" + rowid + "'") ;
    }
    else
    {
        ui->ptText->appendPlainText("   病志号 " + card_no + " 数据传输失败。");
    }

    ui->ptText->appendPlainText("    病志号 " + card_no + " 数据传输成功。");
    qApp->processEvents();  //刷新显示

}
void Form_dzbl::mjzzf(int currentRow)
{
    //自费门急诊患者信息

    logFile->open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(logFile);

    qApp->processEvents();  //刷新显示
    QString clinic_code, card_no, reg_date, dept_code, dept_name , rowid ;

    if(currentRow < 0)  {   //单个上传
        clinic_code = mdList.record(ui->tvList->currentIndex().row()).value(5).toString();
        card_no = mdList.record(ui->tvList->currentIndex().row()).value(2).toString();
        reg_date = mdList.record(ui->tvList->currentIndex().row()).value(0).toString();
        dept_code = mdList.record(ui->tvList->currentIndex().row()).value(9).toString();
        dept_name = mdList.record(ui->tvList->currentIndex().row()).value(4).toString();
        rowid = mdList.record(ui->tvList->currentIndex().row()).value(10).toString();

    }else{ //批量上传

        //QMessageBox::information(this,"Note",QString::number(currentRow));
        clinic_code = mdList.record(currentRow).value(4).toString();
        card_no = mdList.record(currentRow).value(1).toString();
        reg_date = mdList.record(currentRow).value(0).toString();
        dept_code = mdList.record(currentRow).value(8).toString();
        dept_name = mdList.record(currentRow).value(3).toString();
        rowid = mdList.record(currentRow).value(9).toString();
    }

    ui->ptText->appendPlainText("病志号 " + card_no + " 开始数据传输...");
    qApp->processEvents();  //刷新显示

    //提取挂号信息
    if( !isAll ){
        ui->ptText->appendPlainText("病志号 " + card_no + ", " + mdList.record(currentRow).value(2).toString()+ " 提取挂号信息...");
        qApp->processEvents();  //刷新显示
    }

    sq = "select r.clinic_code as mdtrt_sn  , r.card_type, r.idenno, r.name , to_char(r.reg_date, 'yyyy-mm-dd') "
         " from fin_opr_register r  where clinic_code = '" + clinic_code + "'";

    if(!qro->exec(sq)){
        QMessageBox::information(this,"错误", card_no + " 提取挂号信息SQL执行失败！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 自费 : " + card_no + " 提取挂号信息SQL执行失败\r\n";
        logFile->flush();
        logFile->close();

        return;
    }
    if(!qro->next()){
        ui->ptText->appendPlainText("病志号 " + card_no + " 提取不到挂号信息！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 自费 : " + card_no + " 找不到挂号信息！\r\n";

    }

    QJsonDocument d;
    QJsonObject jo_tmp;
    QJsonObject jo_mdtrtinfo;
    //挂号
    jo_mdtrtinfo.insert("fixmedins_mdtrt_id", qro->value(0).toString());	//医药机构就诊ID	字符型	30
    jo_mdtrtinfo.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型	30
    jo_mdtrtinfo.insert("fixmedins_name", pub::hos_name);//	定点医药机构名称	字符型	200
    jo_mdtrtinfo.insert("psn_cert_type", qro->value(1).toString());	//	人员证件类型	字符型	6
    jo_mdtrtinfo.insert("certno", qro->value(2).toString());	//	证件号码	字符型	600
    jo_mdtrtinfo.insert("psn_name", qro->value(3).toString());	//	人员姓名	字符型	50
    jo_mdtrtinfo.insert("med_type", "11");//	医疗类别	字符型	6
    jo_mdtrtinfo.insert("begntime", qro->value(4).toString());	//	开始时间	日期型

    //诊断
    QJsonArray ja_diseinfo ;

    ui->ptText->appendPlainText(" 提取病历信息...");
    qApp->processEvents();  //刷新显示


    sq="select zd1, zd1c, doct_code, dept_code, date_format(diag_date, '%Y-%m-%d %H:%i:%S'),ys "
       " from ys_bz_e_rec r "
       " where clinic_code = '" + clinic_code + "'";
    qrm->exec(sq);

    if(!qrm->next())
    {
        ui->ptText->appendPlainText(" 找不到关联的诊断信息！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 自费 : " + card_no + " 找不到关联的诊断信息！\r\n";
        logFile->flush();
        logFile->close();
        return;
    }
    if(qrm->value(1).toString().isEmpty() || qrm->value(1).isNull())
    {
        ui->ptText->appendPlainText(" 诊断信息不完整！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 自费 : " + card_no + " 诊断信息不完整\r\n";
        logFile->flush();
        logFile->close();
        return;
    }

    jo_tmp.insert("diag_type", "1");//	诊断类别	字符型	3	Y	Y 1西医，2中医病，3中医症
    jo_tmp.insert("diag_srt_no", 1);//	诊断排序号	数值型	2		Y
    jo_tmp.insert("diag_code", qrm->value(1).toString());//	诊断代码	字符型	30		Y
    jo_tmp.insert("diag_name", qrm->value(0).toString());//	诊断名称	字符型	100		Y
    jo_tmp.insert("diag_dept", qrm->value(3).toString());//	诊断科室	字符型	50		Y
    jo_tmp.insert("diag_dr_code", qrm->value(2).toString());//	诊断医生编码	字符型	30		Y
    jo_tmp.insert("diag_dr_name", qrm->value(5).toString());//	诊断医生姓名	字符型	50		Y
    jo_tmp.insert("diag_time", qrm->value(4).toString());//	诊断时间	日期时间型			Y
    jo_tmp.insert("vali_flag", "1");//	有效标志	字符型	3	Y	Y

    ja_diseinfo << jo_tmp;

    QJsonArray ja_feedetail;

    //费用明细
    ui->ptText->appendPlainText(" 提取费用明细信息...");
    qApp->processEvents();  //刷新显示

    sq="select sequence_no, to_char(oper_date,'yyyy-mm-dd hh24:mi:ss') ,QTY, unit_price, own_cost,"
       "exec_dpcd, exec_dpnm,doct_code, doct_name, FEE_CODE, item_code, item_name"
       " from met_ord_recipedetail "
       " where charge_flag = '1' "
       " and status <>'3' "
       " and status <>'4' "
       " and clinic_code='"
            + clinic_code
            + "' order by drug_flag, oper_date";
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error", qro->lastError().text());
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 自费 : " + card_no + " 费用明细SQL执行失败\r\n";
        logFile->flush();
        logFile->close();
        return;
    }
    if(!qro->next()){
        ui->ptText->appendPlainText(" 找不到有效的医师处方内容！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 自费 : " + card_no + " 找不到有效医师处方内容\r\n";
        logFile->flush();
        logFile->close();
        return;
    }

    //qro->first();   //Data index reset.

    while(true){
        jo_tmp = d.object();

        jo_tmp.insert("fixmedins_mdtrt_id", clinic_code);//	医药机构就诊ID	字符型	30		Y
        jo_tmp.insert("med_type", "11");//	医疗类别	字符型	6	Y	Y
        jo_tmp.insert("bkkp_sn", qro->value(0).toString());//	记账流水号	字符型	30		Y
        jo_tmp.insert("fee_ocur_time", qro->value(1).toString());//	费用发生时间	日期时间型			Y
        jo_tmp.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型	30		Y
        jo_tmp.insert("fixmedins_name", pub::hos_name);//	定点医药机构名称	字符型	200		Y
        jo_tmp.insert("cnt", qro->value(2).toDouble());//	数量	数值型	16,4		Y
        jo_tmp.insert("pric", qro->value(3).toDouble());//	单价	数值型	16,6		Y
        jo_tmp.insert("det_item_fee_sumamt", qro->value(4).toDouble());//	明细项目费用总额	数值型	16,2		Y
        jo_tmp.insert("bilg_dept_codg", qro->value(5).toString());//	开单科室编码	字符型	30		Y
        jo_tmp.insert("bilg_dept_name", qro->value(6).toString());//	开单科室名称	字符型	100		Y
        jo_tmp.insert("bilg_dr_code", qro->value(7).toString());//	开单医生编码	字符型	30		Y
        jo_tmp.insert("bilg_dr_name", qro->value(8).toString());//	开单医师姓名	字符型	50		Y

        QString fee_code, fee_name;
        switch (qro->value(8).toInt()) {

        case 1: fee_code = "09"; fee_name = "西药" ; break;
        case 2: fee_code = "11"; fee_name = "中成药" ; break;
        case 4: fee_code = "04"; fee_name = "检验" ; break;
        case 5: fee_code = "05"; fee_name = "治疗" ; break;
        case 6: fee_code = "02"; fee_name = "诊察" ; break;
        case 7: fee_code = "03"; fee_name = "检查" ; break;
        default : fee_code = "14"; fee_name = "其他" ; break;

        }
        jo_tmp.insert("med_chrgitm_type", fee_code);//	医疗收费项目类别	字符型	6	Y	Y

        QString med_code = qro->value(10).toString();
        QString med_name = qro->value(11).toString();
        sq = "select med_list_codg ,his_name, fixmedins_hilist_name from fin_com_compare where"
             " fixmedins_hilist_id = '" + med_code +"'";
        qrot->exec(sq);
        if(!qrot->next())
        {
            ui->ptText->appendPlainText( med_name + "/" + med_code + " 找不到对照信息！");
            text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                        << " 自费 : " + card_no + "," + med_name + "," + med_code + " 找不到对照信息\r\n";
            logFile->flush();
            logFile->close();
            return;
        }
        jo_tmp.insert("med_list_codg", qrot->value(0).toString());//	医疗目录编码	字符型	50		Y
        jo_tmp.insert("medins_list_codg", med_code);//	医药机构目录编码	字符型	150		Y
        jo_tmp.insert("medins_list_name", qrot->value(1).toString());//	医药机构目录名称	字符型	100		Y
        jo_tmp.insert("prodname", qrot->value(1).toString());//	商品名	字符型	200		Y

        ja_feedetail << jo_tmp; //

        if(!qro->next()){
            break;
        }
    }


    //数据准备完成，开始传输

    ui->ptText->appendPlainText(" 数据准备完成，开始传输...");
    qApp->processEvents();  //刷新显示

    QJsonObject in;
    in.insert("mdtrtinfo", jo_mdtrtinfo);
    in.insert("diseinfo", ja_diseinfo);
    in.insert("feedetail", ja_feedetail);
    qDebug()<<in;
    if(call_noRet("4205",in, clinic_code))
    {
        ui->ptText->appendPlainText(" 传输数据结束标志...");

        in = d.object();
        in.insert("fixmedins_mdtrt_id", clinic_code);//	医药机构就诊ID	字符型
        in.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型
        in.insert("cplt_flag", "1");//	定完成标志	字符型	6		Y
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 自费 : " + QJsonDocument(in).toJson() + "\r\n";

        if(call_noRet("4203",in, clinic_code))
        {
            ui->ptText->appendPlainText("    病志号 " + card_no + " 数据传输成功。");
            qrot->exec( "update fin_opr_register set upld_flg0 = '1' where rowid = '" + rowid + "'") ;
        }
        else
        {
            ui->ptText->appendPlainText("   病志号 " + card_no + " 数据结束标志传输失败。");
        }
    }
    else
    {
        ui->ptText->appendPlainText("   病志号 " + card_no + " 基础数据传输失败。");
    }
    logFile->flush();
    logFile->close();
    qApp->processEvents();  //刷新显示
}

void Form_dzbl::mjzyb(int currentRow)
{
    //医保门急诊患者信息
    logFile->open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(logFile);

    qApp->processEvents();  //刷新显示
    QString clinic_code, card_no, reg_date, dept_code, dept_name , rowid ;

    if(currentRow < 0)  {   //单个上传
        clinic_code = mdList.record(ui->tvList->currentIndex().row()).value(5).toString();
        card_no = mdList.record(ui->tvList->currentIndex().row()).value(2).toString();
        reg_date = mdList.record(ui->tvList->currentIndex().row()).value(0).toString();
        dept_code = mdList.record(ui->tvList->currentIndex().row()).value(9).toString();
        dept_name = mdList.record(ui->tvList->currentIndex().row()).value(4).toString();
        rowid = mdList.record(ui->tvList->currentIndex().row()).value(10).toString();

    }else{ //批量上传

        //QMessageBox::information(this,"Note",QString::number(currentRow));
        clinic_code = mdList.record(currentRow).value(4).toString();
        card_no = mdList.record(currentRow).value(1).toString();
        reg_date = mdList.record(currentRow).value(0).toString();
        dept_code = mdList.record(currentRow).value(8).toString();
        dept_name = mdList.record(currentRow).value(3).toString();
        rowid = mdList.record(currentRow).value(9).toString();
    }

    ui->ptText->appendPlainText("病志号 " + card_no + " 开始数据传输...");
    qApp->processEvents();  //刷新显示


    QJsonObject in;
    if(!putBaseIn( in, "4301") ){
        logFile->flush();
        logFile->close();
        return;
    }
    //提取挂号信息
    if( !isAll ){
        ui->ptText->appendPlainText("病志号 " + card_no + ", " + mdList.record(currentRow).value(2).toString()+ " 提取挂号信息...");
        qApp->processEvents();  //刷新显示
    }

    sq = "select r.clinic_code as mdtrt_sn  , (select mdtrt_id  from fin_ipr_siinmaininfo where balance_no = '0' and inpatient_no = r.clinic_code)  as mdtrt_id,"
         " (select  psn_no from fin_ipr_siinmaininfo where balance_no = '0' and inpatient_no = r.clinic_code) as psn_no  , r.medical_type as rgst_type_code, "
         " r.ynbook as rgst_way_code, r.diag_fee as rgst_serv_fee, ordr_way_code, case when  r.trans_type = '2' then '1' else '0' end  as retnr_flag,"
         " r.ynfr as fstdiag_flag,  r.ynsee as mdtrt_flag, r.oper_date as rgst_retnr_time, r.medfee_paymtd as medfee_paymtd_code, '1' as vali_flag"
         " from fin_opr_register r  where clinic_code = '" + clinic_code + "'";

    if(!qro->exec(sq)){
        QMessageBox::information(this,"错误", card_no + " 提取挂号信息SQL执行失败！");
        qDebug()<<sq;
    }
    if(!qro->next()){
        ui->ptText->appendPlainText("病志号 " + card_no + " 提取不到挂号信息！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 4301 : 病志号 " + card_no + " 提取不到挂号信息！\r\n";
        logFile->flush();
        logFile->close();
        return;
    }

    QJsonDocument d;
    QJsonObject inpu,inpud;

    inpu.insert("mdtrt_sn", qro->value(0).toString());  //就医流水号
    inpu.insert("mdtrt_id", qro->value(1).toString());  //就诊ID
    inpu.insert("psn_no", qro->value(2).toString());    //人员编号
    inpu.insert("rgst_type_code", qro->value(3).toString());    //挂号类别代码
    inpu.insert("rgst_way_code", qro->value(4).toString());     //挂号方式代码
    inpu.insert("rgst_serv_fee", QString::asprintf("%.2f",qrot->value(5).toDouble()));     //挂号费/医事服务费
    inpu.insert("ordr_way_code", qro->value(6).toString());     //预约途径代码
    inpu.insert("retnr_flag", qro->value(7).toString());        //退号标志
    inpu.insert("fstdiag_flag", qro->value(8).toString());      //初诊标志
    inpu.insert("mdtrt_flag", qro->value(9).toString());        //就诊标志
    inpu.insert("rgst_retnr_time", qro->value(10).toString());      //挂号/退号时间
    inpu.insert("medfee_paymtd_code", qro->value(11).toString());   //医疗费用支付方式代码
    inpu.insert("vali_flag", qro->value(12).toString());    //有效标志

    inpud.insert("rgstinfo",inpu);  //写入挂号结点

    //病历信息
    QJsonArray jsarCaseinfo;
    if( !isAll ){
        ui->ptText->appendPlainText(" 提取病历信息...");
        qApp->processEvents();  //刷新显示
    }

    sq="select * from ys_bz_e_rec where clinic_code = '" + clinic_code + "'";
    qrm->exec(sq);
    qrm->next();

    inpu = d.object();  //清空json变量
    inpu.insert("mdtrt_date", reg_date);    //就诊日期	日期型
    inpu.insert("chfcomp", qrm->value("hzzs").toString());    //	主诉	字符型
    //inpu.insert("attk_date_time", reg_date);    //	发病日期时间	日期时间型
    inpu.insert("mdtrt_rea", qrm->value("jzyy").toString());    //	就诊原因	字符型
    inpu.insert("illhis", qrm->value("xbs").toString());    //	病史	字符型
    inpu.insert("algs", qrm->value("gms").toString());    //	过敏史	字符型
    //inpu.insert("aise_code", reg_date);    //	过敏源代码	字符型
    inpu.insert("phex", qrm->value("tgjc").toString());    //	查体	字符型
    //inpu.insert("disa_info_code", reg_date);    //	残疾情况代码	字符型
    //inpu.insert("symp_name", reg_date);    //	症状名称	字符型
    //inpu.insert("symp_code", reg_date);    //	症状代码	字符型
    QString dspo = qrm->value("medical_plan").toString() + qrm->value("yz").toString(); //+ ""
    inpu.insert("dspo_opnn", dspo);    //	处置意见	字符型
    inpu.insert("dept_code", dept_code);    //	科室代码	字符型
    inpu.insert("dept_name", dept_name);    //	科室名称	字符型
    inpu.insert("vali_flag", "1");    //	有效标志	字符型

    jsarCaseinfo << inpu;

    inpud.insert("caseinfo", jsarCaseinfo);  //写入病历信息结点



    //提取诊断信息
    QJsonArray jsarDiseinfo;
    inpu = d.object();  //清空json变量
    QJsonObject diag;

    inpu.insert("maindiag_flag", "1");    //主诊断标志

    inpu.insert("diag_code", qrm->value("zd1c").toString());    //西医诊断代码
    inpu.insert("diag_name", qrm->value("zd1").toString());    //西医诊断名称

    if(qrm->value("zyzd1").toString().isEmpty())
    {
        inpu.insert("tcm_diag_flag", "");    //中医诊断标志
        inpu.insert("tcm_dise_code", "");    //中医病名代码
        inpu.insert("tcm_dise_name", "");    //中医病名名称
        inpu.insert("tcmsymp_code", "");    //中医证候代码
        inpu.insert("tcmsymp", "");    //中医证候
    }
    else
    {
        inpu.insert("tcm_diag_flag", "1");    //中医诊断标志
        inpu.insert("tcm_dise_code", qrm->value("zyzd1c").toString());    //中医病名代码
        inpu.insert("tcm_dise_name", qrm->value("zyzd1").toString());    //中医病名名称
        inpu.insert("tcmsymp_code", qrm->value("zyzh1c").toString());    //中医证候代码
        inpu.insert("tcmsymp", qrm->value("zyzh1").toString());    //中医证候
    }

    inpu.insert("vali_flag", "1");    //有效标志
    jsarDiseinfo << inpu;   //send jsonObject into jsonArray

    if(!qrm->value("zd2").toString().isEmpty())
    {
        inpu.insert("maindiag_flag", "0");    //主诊断标志

        inpu.insert("diag_code", qrm->value("zd2c").toString());    //西医诊断代码
        inpu.insert("diag_name", qrm->value("zd2").toString());    //西医诊断名称

        if(qrm->value("zyzd2").toString().isEmpty())
        {
            inpu.insert("tcm_diag_flag", "");    //中医诊断标志
            inpu.insert("tcm_dise_code", "");    //中医病名代码
            inpu.insert("tcm_dise_name", "");    //中医病名名称
            inpu.insert("tcmsymp_code", "");    //中医证候代码
            inpu.insert("tcmsymp", "");    //中医证候
        }
        else
        {
            inpu.insert("tcm_diag_flag", "1");    //中医诊断标志
            inpu.insert("tcm_dise_code", qrm->value("zyzd2c").toString());    //中医病名代码
            inpu.insert("tcm_dise_name", qrm->value("zyzd2").toString());    //中医病名名称
            inpu.insert("tcmsymp_code", qrm->value("zyzh2c").toString());    //中医证候代码
            inpu.insert("tcmsymp", qrm->value("zyzh2").toString());    //中医证候
        }

        inpu.insert("vali_flag", "1");    //有效标志
        jsarDiseinfo << inpu;   //send jsonObject into jsonArray

    }

    if(!qrm->value("zd3").toString().isEmpty())
    {
        inpu.insert("maindiag_flag", "0");    //主诊断标志

        inpu.insert("diag_code", qrm->value("zd3c").toString());    //西医诊断代码
        inpu.insert("diag_name", qrm->value("zd3").toString());    //西医诊断名称

        if(qrm->value("zyzd3").toString().isEmpty())
        {
            inpu.insert("tcm_diag_flag", "");    //中医诊断标志
            inpu.insert("tcm_dise_code", "");    //中医病名代码
            inpu.insert("tcm_dise_name", "");    //中医病名名称
            inpu.insert("tcmsymp_code", "");    //中医证候代码
            inpu.insert("tcmsymp", "");    //中医证候
        }
        else
        {
            inpu.insert("tcm_diag_flag", "1");    //中医诊断标志
            inpu.insert("tcm_dise_code", qrm->value("zyzd3c").toString());    //中医病名代码
            inpu.insert("tcm_dise_name", qrm->value("zyzd3").toString());    //中医病名名称
            inpu.insert("tcmsymp_code", qrm->value("zyzh3c").toString());    //中医证候代码
            inpu.insert("tcmsymp", qrm->value("zyzh3").toString());    //中医证候
        }

        inpu.insert("vali_flag", "1");    //有效标志
        jsarDiseinfo << inpu;   //send jsonObject into jsonArray
    }

    inpud.insert("diseinfo", jsarDiseinfo);  //写入诊断信息结点

    inpu = d.object();  //清空json变量

    //检索医师处方内容,诊断信息
    if( !isAll ){
        ui->ptText->appendPlainText(" 提取医师处方内容,诊断信息...");
        qApp->processEvents();  //刷新显示
    }

    sq="select FEE_CODE,recipe_no,charge_flag,CLINIC_CODE,CARD_NO,to_char(REG_DATE,'yyyy-mm-dd') cdt ,ITEM_CODE,ITEM_NAME,"
       "SPECS,DRUG_FLAG,CLASS_CODE,QTY,ITEM_UNIT,ONCE_DOSE,ONCE_UNIT,FREQUENCY_NAME,USAGE_NAME,EXEC_DPNM,DOCT_NAME,LAB_TYPE,"
       "CHECK_BODY,CLINICDIAG_CODE,CLINICDIAG_NAME,CLINICOTHERDIAG1_CODE,CLINICOTHERDIAG1_NAME,CLINICOTHERDIAG2_CODE,"
       "CLINICOTHERDIAG2_NAME ,oper_date ,days"
       " from met_ord_recipedetail "
       " where charge_flag = '1' "
       " and status <>'3' "
       " and status <>'4' "
       " and clinic_code='"
            + clinic_code
            + "' order by drug_flag, oper_date";
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error", qro->lastError().text());
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 4301 : 病志号 " + card_no + sq + " SQL错误！\r\n";
        logFile->flush();
        logFile->close();
        return;

    }
    if(!qro->next()){

        ui->ptText->appendPlainText(" 找不到有效的医师处方内容！！");
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                    << " 4301 : 病志号 " + card_no + " 找不到有效的医师处方内容！\r\n";
        logFile->flush();
        logFile->close();
        return;
    }

    QJsonArray jsarRxinfo;  //处方数据

    while(true){

        //检查处方是否收费
        if( qro->value("charge_flag").toString() == "0"){
            //处方未收费
            if(!qro->next()){   //循环是否结束
                break;
            }
            continue;
        }

        inpu.insert("rxno", qro->value("recipe_no").toString());    //处方号
        inpu.insert("rx_prsc_time", qro->value("oper_date").toString());    //处方开方时间
        inpu.insert("rx_type_code", "1");    //处方类别代码

        int fee_code = qro->value("FEE_CODE").toInt();
        QString fee_name;
        //1 西药 = 11 ， 2 中药 = 12 ，4 化验 = 22，7 检查 = 23 ，5 处置 = 21，
        // 6 留观费 = 21 ，10 器械 = 31 ，11 采血费 = 21， 12 彩色打印照片 = 31, 14 取暖费 = 31 ，22 床位费（床）=31

        switch (fee_code) {
        case 1: fee_code = 11; fee_name = "西药" ; break;
        case 2: fee_code = 12; fee_name = "中成药" ; break;
        case 4: fee_code = 22; fee_name = "检验" ; break;
        case 5: fee_code = 21; fee_name = "治疗" ; break;
        case 6: fee_code = 21; fee_name = "治疗" ; break;
        case 7: fee_code = 23; fee_name = "检查" ; break;
        default: fee_code = 31; fee_name = "其他";
        }

        inpu.insert("rx_item_type_code", QString::number(fee_code));    //处方项目分类代码
        inpu.insert("rx_item_type_name", fee_name);    //处方项目分类名称
        inpu.insert("rx_detl_id", qro->value("ITEM_CODE").toString());    //院内代码
        inpu.insert("rx_detl_name", qro->value("ITEM_NAME").toString());    //院内名称
        //inpu.insert("tcmdrug_type_name", "1");    //中药类别名称
        //inpu.insert("tcmdrug_type_code", "1");    //中药类别代码
        //inpu.insert("tcmherb_foote", "1");    //草药脚注
        //inpu.insert("medn_type_code", "1");    //药物类型代码
        //inpu.insert("medn_type_name", "1");    //药物类型
        //inpu.insert("drug_dosform", "1");    //药品剂型
        //inpu.insert("drug_dosform_name", "1");    //药品剂型名称
        inpu.insert("drug_spec", qro->value("SPECS").toString());    //药品规格
        inpu.insert("drug_used_frqu", qro->value("FREQUENCY_NAME").toString());    //药物使用-频率
        inpu.insert("drug_used_idose ", qro->value("QTY").toString());    //药物使用-总剂量
        inpu.insert("drug_used_sdose", qro->value("ONCE_DOSE").toString());    //药物使用-次剂量
        inpu.insert("drug_used_dosunt", qro->value("ONCE_UNIT").toString());    //药物使用-剂量单位
        //inpu.insert("drug_used_way_code", qro->value("USAGE_NAME").toString());    //药物使用-途径代码
        inpu.insert("drug_medc_way", qro->value("USAGE_NAME").toString());    //药物使用-途径
        //inpu.insert("skintst_dicm", "1");    //皮试判别
        //inpu.insert("medc_begntime", "1");    //用药开始时间
        //inpu.insert("medc_endtime", "1");    //用药停止日期时间
        inpu.insert("medc_days", qro->value("days").toString());    //用药天数
        //inpu.insert("main_medc_flag", "1");    //主要用药标志
        //inpu.insert("urgt_flag", "1");    //加急标志
        //inpu.insert("unif_purc_drug", "1");    //统一采购药品
        //inpu.insert("drug_purc_code", "1");    //药品采购代码
        //inpu.insert("drug_mgt_plaf_code", "1");    //药品管理平台代码
        //inpu.insert("bas_medn_flag", "1");    //基本药物标志
        inpu.insert("vali_flag", "1");    //有效标志

        jsarRxinfo << inpu; //

        if(!qro->next()){
            break;
        }
    }

    inpud.insert("rxinfo", jsarRxinfo);  //写入处方信息结点

    //数据准备完成，开始传输

    if( !isAll ){
        ui->ptText->appendPlainText(" 数据准备完成，开始传输...");
        qApp->processEvents();  //刷新显示
    }
    in.insert("input", inpud);

    text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
                << " 4301 :  " <<QJsonDocument(in).toJson()<<"\r\n";

    QJsonDocument indoc ;
    indoc.setObject(in);
    qDebug()<<"4301 indoc "<<indoc;

    //保存入参日志
    sq = "update com_business set v_in = '"
            + indoc.toJson(QJsonDocument::Compact)
            + "' where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存入参日志失败！");
        qDebug()<<sq;
    }

    QNetworkReply* reply = manager.post(request,indoc.toJson());

    QEventLoop eventLoop;
    QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec(); // 进入等待返回，但ui事件循环依然进行。


    qDebug()<<" request 4301 is returned";

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        logFile->flush();
        logFile->close();
        return ;
    }

    QNetworkReply::NetworkError err = reply->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",reply->errorString());
        logFile->flush();
        logFile->close();
        return ;
    }


    QByteArray bt = reply->readAll();
    QString t = QString::fromLocal8Bit(bt);

    QJsonParseError json_error;
    QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
    if(json_error.error != 0 ){
        QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
        logFile->flush();
        logFile->close();
        return ;
    }
    qDebug()<< "4301 outDoc "<<jsdc;
    QJsonObject jsob = jsdc.object();

    sq = "update com_business set  "
         "tmstmp = now(), "
         " clinic_code = '"
            + clinic_code
             + "', v_out = '"
            + jsdc.toJson(QJsonDocument::Compact)
            + "' , infcode = "
            + QString::number(jsob.value("infcode").toInt())
             +  "  where jyls = '" + currentMsgid + "'";

    if(!qrm->exec(sq)){
        QMessageBox::information(this,"错误","保存出参日志失败！");
        qDebug()<<sq;
    }


    if(jsob.value("infcode").toInt() != 0){
        QString t = jsob.value("err_msg").toString();
        QMessageBox::warning(NULL,"注意","4301 交易失败：" + t );
        text_stream << QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")<< " 4301 : "
                    << t << "\r\n";
        logFile->flush();
        logFile->close();
        return ;
    }

    qro->exec( "update fin_opr_register set upld_flg0 = '1' where rowid = '" + rowid + "'") ;

    if(currentRow < 0)  {   //单个上传
        //QMessageBox::information(this,"注意","操作完成。");
        on_pbSearch_clicked();  // refresh display.
    }
    ui->ptText->appendPlainText("    病志号 " + card_no + " 数据传输成功。");
    logFile->flush();
    logFile->close();
    qApp->processEvents();  //刷新显示

}

void Form_dzbl::on_tvList_doubleClicked(const QModelIndex &index)
{
    on_tvList_clicked(index);
}

void Form_dzbl::on_tvList_clicked(const QModelIndex &index)
{

    ui->ptText->clear();    //清除明细显示
    ui->tbPreview->clear(); //清除明细显示

    QString preview;
    QFile f(":/mzbl.html");
    if(f.open(QFile::ReadOnly)){
        preview = QString::fromUtf8(f.readAll());
        f.close();
    }else{
        QMessageBox::information(this, "note", "cann't open mzbl.html !");
        return;
    }

    QString clinic_code = index.siblingAtColumn(5).data(0).toString();
    QString card_no = index.siblingAtColumn(2).data(0).toString();
    QString dt = index.siblingAtColumn(0).data(0).toString();
    QString dpnm = index.siblingAtColumn(4).data(0).toString();
    QString doct_code = index.siblingAtColumn(14).data(0).toString();
    QString doct_name = index.siblingAtColumn(15).data(0).toString();
    QString see_code = index.siblingAtColumn(16).data(0).toString();

    if(doct_code != see_code)
    {
        doct_code = see_code;
        sq = "select empl_name from com_employee where empl_code = '" + doct_code + "' limit 1";
        qrm->exec(sq);

        qrm->next();
        doct_name = qrm->value(0).toString();
    }

    QString gend = index.siblingAtColumn(11).data(0).toString();

    preview.replace("--姓名--", index.siblingAtColumn(3).data(0).toString());
    preview.replace("--性别--", gend);
    preview.replace("--年龄--", QString::asprintf("%.1f", index.siblingAtColumn(12).data(0).toDouble()));
    preview.replace("--病志号--", index.siblingAtColumn(2).data(0).toString());
    preview.replace("--诊室--", index.siblingAtColumn(4).data(0).toString());

    preview.replace("--就诊时间--", index.siblingAtColumn(8).data(0).toString());
    preview.replace("--主治医生--", doct_name);

    if(ui->rbZfsc->isChecked() || ui->rbMjzzf->isChecked())
    {
        preview.replace("<strong> 医保卡号：</strong> --医保卡号--", "");
    }
    else
    {
        preview.replace("--医保卡号--", index.siblingAtColumn(13).data(0).toString());
    }

    sq="select xmmc, xmjg from ys_bz_e_lib "
       " where clinic_code = '" + clinic_code + "'";
    qrm->exec(sq);
    QString tmp_str = "";
    while(qrm->next())
    {
        if(qrm->value(1).toString().isEmpty())
        {
            //化验无结果
            ui->ptText->appendPlainText("检验项目 " + qrm->value(0).toString() + " 未录入结果!");
            continue;
        }
        tmp_str += qrm->value(0).toString();
        tmp_str += " : ";
        tmp_str += qrm->value(1).toString();
        tmp_str += " ; ";
    }

//    //检查化验，met_chk_lis_result，院内项目
//    sq=" select DISTINCT PACKAGE_NAME,LIS_SUMMARY "
//       " from MET_CHK_LIS_RESULT where clinic_code = '" + clinic_code + "'";
//    qrot->exec(sq);

//    while(qrot->next())
//    {
//        tmp_str += qrot->value("PACKAGE_NAME").toString();
//        tmp_str += " : ";
//        tmp_str += qrot->value("LIS_SUMMARY").toString();
//        tmp_str += " ; ";

//    }

    if(tmp_str.isEmpty())
    {
        preview.replace("<strong> 辅助检查：</strong> <br> --辅助检查-- <br>", "");
    }
    else
    {
        preview.replace("--辅助检查--", tmp_str);
    }


    sq="select * from ys_bz_e_rec r "
       " where clinic_code = '" + clinic_code + "'";
    qrm->exec(sq);
    qrm->next();
    //bool hasRecipe = true;

    preview.replace("--患者主诉--", qrm->value("hzzs").toString());
    preview.replace("--现病史--", qrm->value("xbs").toString());
    preview.replace("--既往史--", qrm->value("jws").toString());
    preview.replace("--过敏史--", qrm->value("gms").toString());
    preview.replace("--个人史--", qrm->value("person_hist").toString());
    preview.replace("--诊疗计划--", qrm->value("medical_plan").toString());
    preview.replace("--医嘱--", qrm->value("yz").toString());
    preview.replace("--家族史--", qrm->value("family_hist").toString());
    preview.replace("--体格检查--", qrm->value("tgjc").toString());

    if(gend == "女")
    {
        preview.replace("--月经史--", qrm->value("menstr_hist").toString());
    }
    else
    {
        preview.replace("<strong> 月经史：</strong> <br> --月经史-- <br>","");
    }

    QString zd = qrm->value("zd1").toString() + " / " + qrm->value("zd1c").toString();
    if(!qrm->value("zd2").toString().isEmpty()){
        zd.append(", " + qrm->value("zd2").toString() + " / " + qrm->value("zd2c").toString());
    }
    if(!qrm->value("zd3").toString().isEmpty()){
        zd.append(", " + qrm->value("zd3").toString() + " / " + qrm->value("zd3c").toString());
    }

    preview.replace("--ICD诊断--", zd);


    //☆‖·¨．◆ .§
    QString zyzd = qrm->value("zyzd1").toString()
            + "["
            + qrm->value("zyzh1").toString()
            + "] / "
            + qrm->value("zyzd1c").toString()
            + "["
            + qrm->value("zyzh1c").toString()
            + "]";

    if(!qrm->value("zyzd2").toString().isEmpty())
    {
        zyzd.append(", "
                  + qrm->value("zyzd2").toString()
                  + "["
                  + qrm->value("zyzh2").toString()
                  + "] / "
                  + qrm->value("zyzd2c").toString()
                  + "["
                  + qrm->value("zyzh2c").toString()
                  + "]");
    }
    if(!qrm->value("zyzd3").toString().isEmpty())
    {
        zyzd.append(", "
                  + qrm->value("zyzd3").toString()
                  + "["
                  + qrm->value("zyzh3").toString()
                  + "] / "
                  + qrm->value("zyzd3c").toString()
                  + "["
                  + qrm->value("zyzh3c").toString()
                  + "]");
    }

    if(zd == " / ")
    {
        ui->ptText->appendPlainText("找不到诊断信息！");
        ui->pbSingle->setEnabled(false);

    }
    else
    {
        ui->pbSingle->setEnabled(true);
        if(ui->rbIcpc->isChecked())
        {

            QString icpczd;
            qrmt->exec("select icpc_name,icpc_code from com_dict_icpc  "
                       " where valid_flag = '1' "
                       " and  nat_code = '" + qrm->value("zd1c").toString() + "'");
            if(!qrmt->next())
            {
                ui->ptText->appendPlainText("找不到诊断 " + qrm->value("zd1").toString() + " 国标编码关联的ICPC编码！");
                return;
            }
            icpczd += qrmt->value(0).toString() + " / " + qrmt->value(1).toString();

            if(!qrm->value("zd2c").toString().isEmpty())
            {
                qrmt->exec("select icpc_name,icpc_code from com_dict_icpc "
                           " where valid_flag = '1' "
                           " and nat_code = '" + qrm->value("zd2c").toString() + "'");
                if(!qrmt->next())
                {
                    ui->ptText->appendPlainText("找不到诊断 " + qrm->value("zd2").toString() + " 国标编码关联的ICPC编码！");
                    return;
                }
                icpczd += ", " + qrmt->value(0).toString() + " / " + qrmt->value(1).toString();
            }

            if(!qrm->value("zd3c").toString().isEmpty())
            {
                qrmt->exec("select icpc_name,icpc_code from com_dict_icpc  "
                           " where valid_flag = '1' "
                           " and  nat_code = '" + qrm->value("zd3c").toString() + "'");
                if(!qrmt->next())
                {
                    ui->ptText->appendPlainText("找不到诊断 " + qrm->value("zd3").toString() + " 国标编码关联的ICPC编码！");
                    return;
                }
                icpczd += ", " + qrmt->value(0).toString() + " / " + qrmt->value(1).toString();
            }
            preview.replace("--ICPC诊断--", icpczd);
            preview.replace("--就诊原因--", qrm->value("jzyy").toString() + " / " + qrm->value("jzyyc").toString());
        }
        else{
            preview.replace("<strong> ICPC诊断：</strong> <br> --ICPC诊断-- <br>", "");
            preview.replace("<strong> 就诊原因：</strong> <br> --就诊原因-- <br>", "");
        }
    }

    if(qrm->value("zyzd1").toString().isEmpty())
    {
        preview.replace("<strong> 中医类证鉴别：</strong> <br> --中医类证鉴别-- <br>", "");
        preview.replace("<strong> 治则：</strong> <br> --治则-- <br>", "");
        preview.replace("<strong> 中医查体：</strong> <br> --中医查体-- <br>", "");
        preview.replace("<strong> 中医诊断：</strong> <br> --中医诊断-- <br>", "");
        preview.replace("<strong> 辨证依据</strong> <br> --辨证依据-- <br>", "");
    }
    else
    {
        preview.replace("--中医类证鉴别--", qrm->value("similar_syndrom").toString());
        preview.replace("--治则--", qrm->value("treat_tr").toString());
        preview.replace("--中医查体--", qrm->value("tgjc_tr").toString());
        preview.replace("--中医诊断--", zyzd);
        preview.replace("--辨证依据--", qrm->value("zybz").toString());
    }

/*
    sq = " select item_name, specs, qty/pack_qty qqty , price_unit, qty/pack_qty * unit_price , "
         "cancel_flag, CONFIRM_CODE, drug_flag "
         " from fin_opb_feedetail f where clinic_code ='"
            + clinic_code + "'  and trans_type = '1' ";  //and drug_flag = '1'
    sq += " and pay_flag = '1' and cancel_flag = '1' and fee_code in ('001','002','003','005') "; //drug_flag
    sq += " and doct_code ='" + doct_code + "' order by mo_order";
    qDebug()<<"提取处方信息："<<sq;
    QString cz;
    qrot->exec(sq);
    if(!qrot->next()){
        ui->ptText->appendPlainText("关联不到有效的药品处方和治疗处方信息！");
        //ui->pbSingle->setEnabled(false);

    }else{
        ui->pbSingle->setEnabled(true);
        while(true){

            //cz.append(qrot->value(7).toString());
            //cz.append(" ");
            cz.append(qrot->value(0).toString());
            cz.append(" ");
            cz.append(qrot->value(1).toString());
            cz.append(" ");
            cz.append(qrot->value(2).toString());
            //cz.append(" ");
            //cz.append(qrot->value(3).toString());
            //cz.append(" ");
            //cz.append(QString::asprintf("%.2f",qrot->value(4).toDouble())+"元");
            if(!qrot->next()){
                break;
            }else{
                //cz.append("<br/>");
                cz.append(" ; ");
            }
        }
    }
    preview.replace("--诊疗计划--", cz);
*/

    if(ui->rbIcpc->isChecked() && ui->pbSingle->isEnabled())
    {
        //20250207，有挂号信息即允许上传
        sq = "select mdtrt_id,psn_no,setl_id from fin_ipr_siinmaininfo where inpatient_no = '"; //balance_no = '1' and
        sq += clinic_code + "'";
        qrot->exec(sq);
        if(!qrot->next())
        {
            ui->ptText->appendPlainText("无关联的医保结算ID！");
            ui->pbSingle->setEnabled(false);
        }
    }
    ui->tbPreview->setHtml(preview);
//    if(!ui->cbUnUpload->isChecked())
//    {

//        if(!ui->rbIcpc->isChecked())
//        {
//            //icpc可以重复上传
//            ui->pbSingle->setEnabled(false);
//        }
//    }
}

bool Form_dzbl::call_noRet(QString busi, QJsonObject &inpu, QString clinic_code)
{
    QJsonObject jsonRet;    //医保交易返回的Json数据
    QString info;   //如果返回错误，保存错误信息

    if( ! pub::call_business(busi, inpu, info, jsonRet, "", true , manager, request, clinic_code))
    {
        QMessageBox::warning(this, "注意", info);
        qDebug()<<busi<<" business return error.";
        qDebug()<<info;
        return false;
    }

    return true;
}

void Form_dzbl::on_rbMjzyb_clicked()
{
    mdList.setQuery("");
    //ui->pbTemp->setVisible(false);
}

void Form_dzbl::on_rbMjzzf_clicked()
{
    mdList.setQuery("");
    //ui->pbTemp->setVisible(false);
}

void Form_dzbl::on_rbIcpc_clicked()
{
    mdList.setQuery("");
    //ui->pbTemp->setVisible(true);
}

void Form_dzbl::on_rbZfsc_clicked()
{
    mdList.setQuery("");
    //ui->pbTemp->setVisible(false);
}

void Form_dzbl::on_pbTemp_clicked()
{

    QString txt;

    QFile f(":/mzbl.html");


    if(f.open(QFile::ReadOnly)){


        txt = QString::fromUtf8(f.readAll());

        f.close();

    }else{

        QMessageBox::information(this, "note", "cann't open mzbl.html !");

        return;

    }

    txt.replace("--姓名--","一段广西文本"); //？？


    ui->tbPreview->setHtml(txt);

}

void Form_dzbl::on_pb4201_clicked()
{
    qApp->processEvents();  //刷新显示
    QString clinic_code, card_no, reg_date, dept_code, dept_name , rowid ;

    clinic_code = mdList.record(ui->tvList->currentIndex().row()).value(5).toString();
    card_no = mdList.record(ui->tvList->currentIndex().row()).value(2).toString();
    reg_date = mdList.record(ui->tvList->currentIndex().row()).value(0).toString();
    dept_code = mdList.record(ui->tvList->currentIndex().row()).value(9).toString();
    dept_name = mdList.record(ui->tvList->currentIndex().row()).value(4).toString();
    rowid = mdList.record(ui->tvList->currentIndex().row()).value(10).toString();


    ui->ptText->appendPlainText("病志号 " + card_no + " 开始数据传输...");
    qApp->processEvents();  //刷新显示



    sq = "select r.clinic_code as mdtrt_sn  , r.card_type, r.idenno, r.name , to_char(r.reg_date, 'yyyy-mm-dd') "
         " from fin_opr_register r  where clinic_code = '" + clinic_code + "'";

    qro->exec(sq);
    qro->next();

    QString psn_cert_type = qro->value(1).toString();
    QString certno = qro->value(2).toString();
    QString psn_name = qro->value(3).toString();

    QJsonDocument d;
    QJsonObject jo_tmp;
    QJsonObject jo_mdtrtinfo;
    //挂号

    QJsonArray ja_feedetail;

    //费用明细
    ui->ptText->appendPlainText(" 提取费用明细信息...");
    qApp->processEvents();  //刷新显示

    sq="select sequence_no, to_char(oper_date,'yyyy-mm-dd hh24:mi:ss') ,QTY, unit_price, own_cost,"
       "exec_dpcd, exec_dpnm,doct_code, doct_name, FEE_CODE, item_code, item_name"
       " from met_ord_recipedetail "
       " where charge_flag = '1' "
       " and status <>'3' "
       " and status <>'4' "
       " and clinic_code='"
            + clinic_code
            + "' order by drug_flag, oper_date";
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error", qro->lastError().text());
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
        return;
    }
    qro->next();
    //while(qro->next()){
    jo_tmp = d.object();

    jo_tmp.insert("mdtrt_sn", clinic_code);//	医药机构就诊ID	字符型	30		Y
    jo_tmp.insert("ipt_otp_no", card_no);//
    jo_tmp.insert("med_type", "11");
    jo_tmp.insert("chrg_bchno", clinic_code);
    jo_tmp.insert("feedetl_sn", qro->value(0).toString());//	记账流水号	字符型	30		Y
    jo_tmp.insert("psn_cert_type", psn_cert_type);
    jo_tmp.insert("certno", certno);
    jo_tmp.insert("psn_name", psn_name);
    jo_tmp.insert("fee_ocur_time", qro->value(1).toString());//	费用发生时间	日期时间型			Y
    //jo_tmp.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型	30		Y
    //jo_tmp.insert("fixmedins_name", pub::hos_name);//	定点医药机构名称	字符型	200		Y
    jo_tmp.insert("cnt", qro->value(2).toDouble());//	数量	数值型	16,4		Y
    jo_tmp.insert("pric", qro->value(3).toDouble());//	单价	数值型	16,6		Y
    jo_tmp.insert("det_item_fee_sumamt", qro->value(4).toDouble());//	明细项目费用总额	数值型	16,2		Y
    jo_tmp.insert("bilg_dept_codg", qro->value(5).toString());//	开单科室编码	字符型	30		Y
    jo_tmp.insert("bilg_dept_name", qro->value(6).toString());//	开单科室名称	字符型	100		Y
    jo_tmp.insert("bilg_dr_codg", qro->value(7).toString());//	开单医生编码	字符型	30		Y
    jo_tmp.insert("bilg_dr_name", qro->value(8).toString());//	开单医师姓名	字符型	50		Y

    QString fee_code, fee_name;
    switch (qro->value(8).toInt()) {

    case 1: fee_code = "09"; fee_name = "西药" ; break;
    case 2: fee_code = "11"; fee_name = "中成药" ; break;
    case 4: fee_code = "04"; fee_name = "检验" ; break;
    case 5: fee_code = "05"; fee_name = "治疗" ; break;
    case 6: fee_code = "02"; fee_name = "诊察" ; break;
    case 7: fee_code = "03"; fee_name = "检查" ; break;
    default : fee_code = "14"; fee_name = "其他" ; break;

    }
    jo_tmp.insert("med_chrgitm_type", fee_code);//	医疗收费项目类别	字符型	6	Y	Y

    QString med_code = qro->value("item_code").toString();
    QString med_name = qro->value("item_name").toString();
    sq = "select med_list_codg ,his_name, fixmedins_hilist_name from fin_com_compare where"
         " fixmedins_hilist_id = '" + med_code +"'";
    qrot->exec(sq);
    //qDebug()<<        sq;
    if(!qrot->next())
    {
        ui->ptText->appendPlainText( med_name + "/" + med_code + " 找不到对照信息！");
        return;
    }
    jo_tmp.insert("med_list_codg", qrot->value(0).toString());//	医疗目录编码	字符型	50		Y
    jo_tmp.insert("medins_list_codg", med_code);//	医药机构目录编码	字符型	150		Y
    jo_tmp.insert("medins_list_name", qrot->value(1).toString());//	医药机构目录名称	字符型	100		Y
    jo_tmp.insert("prodname", qrot->value(1).toString());//	商品名	字符型	200		Y

    //  ja_feedetail << jo_tmp; //



    //}

    jo_mdtrtinfo.insert("feedetail", jo_tmp);

    if(call_noRet("4201", jo_mdtrtinfo, clinic_code))
    {
        ui->ptText->appendPlainText("    病志号 " + card_no + " 数据传输成功。");
        //qrot->exec( "update fin_opr_register set upld_flg0 = '1' where rowid = '" + rowid + "'") ;
    }

    //qDebug()<<jo_mdtrtinfo;

    //QMessageBox::information(this,"ntoe","finished.");
}

void Form_dzbl::on_pushButton_3_clicked()
{
    qApp->processEvents();  //刷新显示
    QString clinic_code, card_no, reg_date, dept_code, dept_name , rowid ;

    clinic_code = mdList.record(ui->tvList->currentIndex().row()).value(5).toString();
    card_no = mdList.record(ui->tvList->currentIndex().row()).value(2).toString();
    reg_date = mdList.record(ui->tvList->currentIndex().row()).value(0).toString();
    dept_code = mdList.record(ui->tvList->currentIndex().row()).value(9).toString();
    dept_name = mdList.record(ui->tvList->currentIndex().row()).value(4).toString();
    rowid = mdList.record(ui->tvList->currentIndex().row()).value(10).toString();


    ui->ptText->appendPlainText("病志号 " + card_no + " 开始数据传输...");
    qApp->processEvents();  //刷新显示



    sq = "select r.clinic_code as mdtrt_sn  , r.card_type, r.idenno, r.name , to_char(r.reg_date, 'yyyy-mm-dd') "
         " from fin_opr_register r  where clinic_code = '" + clinic_code + "'";

    qro->exec(sq);
    qro->next();

    QString psn_cert_type = qro->value(1).toString();
    QString certno = qro->value(2).toString();
    QString psn_name = qro->value(3).toString();

    QJsonDocument d;
    QJsonObject jo_tmp;
    QJsonObject jo_mdtrtinfo;
    //挂号

    QJsonArray ja_feedetail;

    //费用明细
    ui->ptText->appendPlainText(" 提取费用明细信息...");
    qApp->processEvents();  //刷新显示

    sq="select sequence_no, to_char(oper_date,'yyyy-mm-dd hh24:mi:ss') ,QTY, unit_price, own_cost,"
       "exec_dpcd, exec_dpnm,doct_code, doct_name, FEE_CODE, item_code, item_name"
       " from met_ord_recipedetail "
       " where charge_flag = '1' "
       " and status <>'3' "
       " and status <>'4' "
       " and clinic_code='"
            + clinic_code
            + "' order by drug_flag, oper_date";
    if(!qro->exec(sq)){
        QMessageBox::information(this,"error", qro->lastError().text());
        qDebug()<<qro->lastError().text();
        qDebug()<<qro->lastQuery();
        return;
    }
    //qro->next();
    while(qro->next()){
        jo_tmp = d.object();

        jo_tmp.insert("fixmedins_mdtrt_id", clinic_code);//	医药机构就诊ID	字符型	30		Y
        //jo_tmp.insert("ipt_otp_no", card_no);//
        jo_tmp.insert("med_type", "11");
        //jo_tmp.insert("chrg_bchno", clinic_code);
        jo_tmp.insert("bkkp_sn", qro->value(0).toString());//	记账流水号	字符型	30		Y

        //jo_tmp.insert("psn_cert_type", psn_cert_type);
        //jo_tmp.insert("certno", certno);
        //jo_tmp.insert("psn_name", psn_name);

        jo_tmp.insert("fee_ocur_time", qro->value(1).toString());//	费用发生时间	日期时间型			Y
        jo_tmp.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型	30		Y
        jo_tmp.insert("fixmedins_name", pub::hos_name);//	定点医药机构名称	字符型	200		Y
        jo_tmp.insert("cnt", qro->value(2).toDouble());//	数量	数值型	16,4		Y
        jo_tmp.insert("pric", qro->value(3).toDouble());//	单价	数值型	16,6		Y
        jo_tmp.insert("det_item_fee_sumamt", qro->value(4).toDouble());//	明细项目费用总额	数值型	16,2		Y

        jo_tmp.insert("bilg_dept_codg", qro->value(5).toString());//	开单科室编码	字符型	30		Y
        jo_tmp.insert("bilg_dept_name", qro->value(6).toString());//	开单科室名称	字符型	100		Y
        jo_tmp.insert("bilg_dr_code", qro->value(7).toString());//	开单医生编码	字符型	30		Y
        jo_tmp.insert("bilg_dr_name", qro->value(8).toString());//	开单医师姓名	字符型	50		Y

        QString fee_code, fee_name;
        switch (qro->value(8).toInt()) {

        case 1: fee_code = "09"; fee_name = "西药" ; break;
        case 2: fee_code = "11"; fee_name = "中成药" ; break;
        case 4: fee_code = "04"; fee_name = "检验" ; break;
        case 5: fee_code = "05"; fee_name = "治疗" ; break;
        case 6: fee_code = "02"; fee_name = "诊察" ; break;
        case 7: fee_code = "03"; fee_name = "检查" ; break;
        default : fee_code = "14"; fee_name = "其他" ; break;

        }
        jo_tmp.insert("med_chrgitm_type", fee_code);//	医疗收费项目类别	字符型	6	Y	Y

        QString med_code = qro->value("item_code").toString();
        QString med_name = qro->value("item_name").toString();
        sq = "select med_list_codg ,his_name, fixmedins_hilist_name from fin_com_compare where"
             " fixmedins_hilist_id = '" + med_code +"'";
        qrot->exec(sq);
        //qDebug()<<        sq;
        if(!qrot->next())
        {
            ui->ptText->appendPlainText( med_name + "/" + med_code + " 找不到对照信息！");
            return;
        }
        jo_tmp.insert("med_list_codg", qrot->value(0).toString());//	医疗目录编码	字符型	50		Y
        jo_tmp.insert("medins_list_codg", med_code);//	医药机构目录编码	字符型	150		Y
        jo_tmp.insert("medins_list_name", qrot->value(1).toString());//	医药机构目录名称	字符型	100		Y
        jo_tmp.insert("prodname", qrot->value(1).toString());//	商品名	字符型	200		Y

        ja_feedetail << jo_tmp; //

    }

    jo_mdtrtinfo.insert("fsiOwnpayPatnFeeListDDTO", ja_feedetail);

    if(call_noRet("4201A", jo_mdtrtinfo, clinic_code))
    {
        ui->ptText->appendPlainText("    病志号 " + card_no + " 数据传输成功。");
        //qrot->exec( "update fin_opr_register set upld_flg0 = '1' where rowid = '" + rowid + "'") ;
    }

    //qDebug()<<jo_mdtrtinfo;

    //QMessageBox::information(this,"ntoe","finished.");
}

void Form_dzbl::on_pushButton_clicked()
{

    //自费门急诊患者信息
    qApp->processEvents();  //刷新显示
    QString clinic_code, card_no, reg_date, dept_code, dept_name , rowid ;

    clinic_code = mdList.record(ui->tvList->currentIndex().row()).value(5).toString();
    card_no = mdList.record(ui->tvList->currentIndex().row()).value(2).toString();
    reg_date = mdList.record(ui->tvList->currentIndex().row()).value(0).toString();
    dept_code = mdList.record(ui->tvList->currentIndex().row()).value(9).toString();
    dept_name = mdList.record(ui->tvList->currentIndex().row()).value(4).toString();
    rowid = mdList.record(ui->tvList->currentIndex().row()).value(10).toString();



    ui->ptText->appendPlainText("病志号 " + card_no + " 开始数据传输...");
    qApp->processEvents();  //刷新显示


    sq = "select r.clinic_code as mdtrt_sn  , r.card_type, r.idenno, r.name , to_char(r.reg_date, 'yyyy-mm-dd') "
         " from fin_opr_register r  where clinic_code = '" + clinic_code + "'";

    qro->exec(sq);
    qro->next();

    QJsonDocument d;
    QJsonObject jo_tmp;
    QJsonObject jo_mdtrtinfo;
    //挂号
    jo_mdtrtinfo.insert("fixmedins_mdtrt_id", qro->value(0).toString());	//医药机构就诊ID	字符型	30
    jo_mdtrtinfo.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型	30
    jo_mdtrtinfo.insert("fixmedins_name", pub::hos_name);//	定点医药机构名称	字符型	200
    jo_mdtrtinfo.insert("psn_cert_type", qro->value(1).toString());	//	人员证件类型	字符型	6
    jo_mdtrtinfo.insert("certno", qro->value(2).toString());	//	证件号码	字符型	600
    jo_mdtrtinfo.insert("psn_name", qro->value(3).toString());	//	人员姓名	字符型	50
    jo_mdtrtinfo.insert("med_type", "11");//	医疗类别	字符型	6
    jo_mdtrtinfo.insert("begntime", qro->value(4).toString());	//	开始时间	日期型

    jo_mdtrtinfo.insert("vali_flag", "1");
    jo_mdtrtinfo.insert("inhosp_stas", "0");

    sq = "select sum(tot_cost) from fin_opb_invoiceinfo where clinic_code = '" + clinic_code + "'";
    qro->exec(sq);
    qro->next();
    jo_mdtrtinfo.insert("medfee_sumamt", qro->value(0).toDouble());

    //诊断
    QJsonArray ja_diseinfo ;

    ui->ptText->appendPlainText(" 提取病历信息...");
    qApp->processEvents();  //刷新显示


    sq="select zd1, zd1c, doct_code, dept_code, date_format(diag_date, '%Y-%m-%d %H:%i:%S'),ys "
       " from ys_bz_e_rec r "
       " where clinic_code = '" + clinic_code + "'";
    qrm->exec(sq);

    if(!qrm->next())
    {
        ui->ptText->appendPlainText(" 找不到关联的诊断信息！");
        qDebug()<<sq;
        return;
    }
    if(qrm->value(1).toString().isEmpty() || qrm->value(1).isNull())
    {
        ui->ptText->appendPlainText(" 诊断信息不完整！");
        return;
    }

    jo_tmp.insert("inout_diag_type", "2");//	诊断类别	字符型	3	Y	Y 1西医，2中医病，3中医症
    jo_tmp.insert("diag_type", "1");//	诊断类别	字符型	3	Y	Y 1西医，2中医病，3中医症
    jo_tmp.insert("maindiag_flag", "1");//
    jo_tmp.insert("diag_srt_no", 1);//	诊断排序号	数值型	2		Y
    jo_tmp.insert("diag_code", qrm->value(1).toString());//	诊断代码	字符型	30		Y
    jo_tmp.insert("diag_name", qrm->value(0).toString());//	诊断名称	字符型	100		Y
    jo_tmp.insert("vali_flag", "1");//	有效标志	字符型	3	Y	Y

    ja_diseinfo << jo_tmp;

    jo_tmp = d.object();

    jo_tmp.insert("ownPayPatnMdtrtD", jo_mdtrtinfo);
    jo_tmp.insert("ownPayPatnDiagListD", ja_diseinfo);


    if(call_noRet("4202", jo_tmp))
    {
        ui->ptText->appendPlainText("    病志号 " + card_no + " 数据传输成功。");
        //qrot->exec( "update fin_opr_register set upld_flg0 = '1' where rowid = '" + rowid + "'") ;
    }
}

void Form_dzbl::on_pushButton_7_clicked()
{
    qApp->processEvents();  //刷新显示
    QString clinic_code, card_no, reg_date, dept_code, dept_name , rowid ;

    clinic_code = mdList.record(ui->tvList->currentIndex().row()).value(5).toString();
    card_no = mdList.record(ui->tvList->currentIndex().row()).value(2).toString();
    reg_date = mdList.record(ui->tvList->currentIndex().row()).value(0).toString();
    dept_code = mdList.record(ui->tvList->currentIndex().row()).value(9).toString();
    dept_name = mdList.record(ui->tvList->currentIndex().row()).value(4).toString();
    rowid = mdList.record(ui->tvList->currentIndex().row()).value(10).toString();


    QJsonDocument d;
    QJsonObject jo_tmp;
    QJsonObject jo_mdtrtinfo;

    jo_tmp.insert("fixmedins_mdtrt_id", clinic_code);
    jo_tmp.insert("fixmedins_code", pub::hos_ybbh);

    jo_tmp.insert("feedetail", jo_tmp);


    if(call_noRet("4204", jo_tmp))
    {
        ui->ptText->appendPlainText("    病志号 " + card_no + " 数据传输成功。");
        //qrot->exec( "update fin_opr_register set upld_flg0 = '1' where rowid = '" + rowid + "'") ;
    }


}

void Form_dzbl::on_pushButton_2_clicked()
{
    qApp->processEvents();  //刷新显示
    QString clinic_code, card_no, reg_date, dept_code, dept_name , rowid ;

    clinic_code = mdList.record(ui->tvList->currentIndex().row()).value(5).toString();
    card_no = mdList.record(ui->tvList->currentIndex().row()).value(2).toString();
    reg_date = mdList.record(ui->tvList->currentIndex().row()).value(0).toString();
    dept_code = mdList.record(ui->tvList->currentIndex().row()).value(9).toString();
    dept_name = mdList.record(ui->tvList->currentIndex().row()).value(4).toString();
    rowid = mdList.record(ui->tvList->currentIndex().row()).value(10).toString();

    QJsonDocument d;
    QJsonObject in;
    //in = d.object();
    in.insert("fixmedins_mdtrt_id", clinic_code);//	医药机构就诊ID	字符型
    in.insert("fixmedins_code", pub::hos_ybbh);//	定点医药机构编号	字符型
    in.insert("cplt_flag", "1");//	定完成标志	字符型	6		Y

    if(call_noRet("4203",in))
    {
        ui->ptText->appendPlainText("    病志号 " + card_no + " 数据传输成功。");
        qrot->exec( "update fin_opr_register set upld_flg0 = '1' where rowid = '" + rowid + "'") ;
    }
    else
    {
        ui->ptText->appendPlainText("   病志号 " + card_no + " 数据结束标志传输失败。");
    }
}

void Form_dzbl::on_cbYb_clicked()
{

}
